2012-03-21 72 views
-3

可能重复:
What exactly does @synthesize do?
Can someone explain this @synthesize syntax?@synthesize羽毛= _feathers?

@interface Duck : NSObject { 

    NSArray *_feathers; 

} 
@property (nonatomic,retain) NSArray *feathers; 

@end 

@implementation Duck 

@synthesize feathers=_feathers; 

@end 

我想知道究竟是什么,当你做@synthesize羽毛= _feathers要去?

+1

你应该看看这个问题http://stackoverflow.com/questions/822487/how-在可变目标-c-class-work前面加一个下划线 – Sakares 2012-03-21 08:23:48

+1

开始阅读[Objective-C](https://developer.apple.com/library /ios/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html)文档。特别是关于[属性]的部分(https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101- SW1) – rckoenes 2012-03-21 08:24:46

+0

除了Apple的文档,有些搜索可以帮助你 - 即使在这个网站。就在昨天,我回答了同样的问题:http://stackoverflow.com/questions/9771434/iphone-instance-variable-issue/9771696#9771696 – MrTJ 2012-03-21 08:34:40

回答

1

你的情况(因为你的财产是非原子)

@synthesize feathers=_feathers; 

等于

- (void)setFeathers:(NSArray *)newFeathers 
{ 
    if (newFeathers != _feathers) 
    { 
     [_feathers release]; 
     _feathers = [newFeathers retain]; 
    } 
} 

- (NSArray *)feathers 
{ 
    return feathers_; 
} 
+2

不完全 - 你也必须检查看看'_fathers!=父亲'在在第一次释放时,setter会错误地释放父对象。 (处理这个问题的另一种方法是'autorelease'而不是'release') – deanWombourne 2012-03-21 08:36:45

+1

@deanWombourne或者在释放旧的值之前保留新值,这样如果它是相同的对象,retainCount不会下降到0 。 – 2013-03-11 00:32:08

+0

@ SlippD.Thompson这就是我的意思:) - 你的解释虽然更好! – deanWombourne 2013-03-11 19:29:17