2010-07-25 59 views
6

我想在Objective-C中編寫我的第一個類,並且我想將NSString對象作爲參數傳遞給類的方法,但是我得到一個錯誤,指出「不能使用對象作爲參數傳遞給方法」。所以我的問題是如何將字符串作爲參數傳遞給方法?這裏是我的代碼謂我試圖去工作:如何傳遞字符串作爲objective-c中的方法參數?

#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 [email protected]", 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; 
} 

回答

15

你需要一個指向您的字符串對象的手。所以你需要添加一個*到參數的類型:

f.e.

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

,並在實施

+0

是完全工作的同時,非常感謝您的幫助,我一直在尋找答案的網站,你是唯一一個誰已經能夠回答我。所以謝謝一堆 – Joe 2010-07-25 01:44:25

相關問題