2011-07-27 78 views
4

我不能在目標c中做到這一點嗎?吸氣劑和吸氣劑不工作目標c

@interface Foo : NSObject { 
    int apple; 
    int banana;   
} 

@property int fruitCount; 
@end 

@implementation Foo 
@synthesize fruitCount; //without this compiler errors when trying to access fruitCount 

-(int)getFruitCount { 
     return apple + banana; 
} 

-(void)setFruitCount:(int)value { 
     apple = value/2; 
     banana = value/2; 
} 

@end 

我使用的類是這樣的:

Foo *foo = [[Foo alloc] init]; 
foo.fruitCount = 7; 

但是我的getter和setter的沒有得到調用。如果我改爲寫:

@property (getter=getFruitCount, setter=setFruitCount:) int fruitCount; 

我的getter被調用,但是setter仍然沒有被調用。我錯過了什麼?

感謝,

回答

9

你的語法是有點過了...... 定義自己的實施屬性訪問你的榜樣,使用以下命令:

@implementation Foo 
@dynamic fruitCount; 

-(int)fruitCount { 
    return apple + banana; 
} 
-(void)setFruitCount:(int)value { 
     apple = value/2; 
     banana = value/2; 
} 

@end 

使用@synthesize告訴編譯器使默認訪問器,在這種情況下顯然不需要。 @dynamic向編譯器表明您將編寫它們。在Apple的文檔中曾經有一個很好的例子,但它在4.0 SDK更新中被破壞了......希望有幫助!

+0

原來我在我的setter名稱中有一個拼寫錯誤,直到我將它設置爲@dynamic並獲得了一個sigbart,因爲我缺少setter方法,所以我沒有找到它。再次感謝。 – odyth