In Objective-C with ARC, is it true that we usuall

2019-02-05 01:06发布

问题:

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