简体   繁体   中英

How do I pass a string as a method parameter in objective-c?

I am trying to write my first class in objective-c and i want to pass an NSString object as a parameter in a method of the class, however i get an error saying that "can not use an object as parameter to a method". So my question is how do you pass a string as a parameter to a method? here is my code tht i am trying to get to work:

#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;
}

You need to hand in a pointer to your string object. So you need to add a * to the type of the parameter:

fe

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

and the same in the implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM