如何在Objective-C中将字符串作为方法参数传递?

6

我正在尝试编写我的第一个Objective-C类,并希望将NSString对象作为参数传递给该类的方法,但是我收到了一个错误,提示“无法将对象用作方法的参数”。那么我的问题是如何将字符串作为参数传递给方法?这是我想要使其正常工作的代码:

#import <Foundation/Foundation.h>

@interface Car
{
    NSString *color;
    NSString *make;
    int year;
}    

- (void) print;
- (void) setColor: (NSString) c;
- (void) setMake: (NSString) m;
- (void) setYear: (int) y;


@end

@implementation Car

- (void) print
{
    NSLog(@"The $d Ford %@ is $@.", year, make, color);
}

- (void) setColor: (NSString) c
{
    color=c;
}

- (void) setMake: (NSString) m
{
    make=m;
}

- (void) setYear: (int) y
{
    year=y;
}


@end



int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Car *car= [Car new];

    [car setColor:@"blue"];
    [car setMake:@"Bronco"];
    [car setYear:1992]

    [car print];
    [car release];

    [pool drain];
    return 0;
}
1个回答

19
你需要提交一个指向你的字符串对象的指针。因此,你需要在参数类型前面添加*号:
例如:
- (void) print;
- (void) setColor:(NSString *) c;
- (void) setMake:(NSString *) m;
- (void) setYear:(int) y;

在实现中同样如此


完全起作用了,非常感谢你的帮助。我一直在网上搜索答案,你是唯一能够回答我的人。所以非常感谢。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接