In Objective-C with ARC, is it true that we usually only need to specify nonatomic as property attributes?

廉价感情. 提交于 2019-11-29 09:23:26

问题


It is strange that in Big Nerd Ranch iOS 5 book (p.73) and Programming iOS 5 book (O'Reilly, p.314) (updadte: even Kochan's Objective-C book Fourth edition), in the context of ARC, they say the default for properties attribute is assign... But Apple's documentation says the default is strong.

I also tried a simple program where if I don't specify strong, the program works ok, and if I specify strong, it works the same, and when assign is used instead, the compiler shows a warning, so it seems the default is indeed strong.

So if most of the time, we want

@property (nonatomic, readwrite, strong) NSMutableArray *foo;

then we can just write

@property (nonatomic) NSMutableArray *foo;

as the other two (readwrite and strong) are the default?


回答1:


readwrite and strong, are indeed the default under ARC*. Under manual reference counting, assign was (is) the default. I prefer to explicitly specify these, because it makes it clearer what the @property's parameters are instead of relying on the person reading the code knowing what the defaults are.

*strong is the default assuming you've either let the compiler synthesize an instance variable for you, or have declared an instance variable without an explicit ownership qualifier (in which case the ivar is __strong by default anyway). Otherwise, the default property ownership type matches the ownership qualifier in the ivar's declaration. So, if you explicitly declare an ivar with __weak, then declare an @property for it without an ownership qualifier, the synthesized property will be weak. This is all documented in the Clang ARC documentation.




回答2:


By default, an object property is strong, atomic, readwrite. See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html



来源:https://stackoverflow.com/questions/11041207/in-objective-c-with-arc-is-it-true-that-we-usually-only-need-to-specify-nonatom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!