I am new to iOS development in general and have never dealt with manual reference counting (retain, release, autorelease). As such I don't have a good understanding of what magic ARC is performing.
I thought I understood until I was asked what type of ownership (weak
, strong
, assign
, etc) should be given to a readonly property pointing at an object, such as:
@property (readonly,nonatomic) NSString* name;
I read here
Questions about a readonly @property in ARC that leaving off the strong
/weak
won't actually compile unless you specify a backing variable when you @synthesize
the property; I just so happened to be specifying a backing ivar like this:
@synthesize name = _name;
Now I understand that the default 'lifetime qualifier' of a variable is strong, from here: http://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4
So to cut a long story short - I am indirectly defining my property as (readonly,nonatomic,strong)
as the _name
ivar is implicitly declared as __strong
.
I have a few questions:
Is strong
the correct lifetime qualifier to use? I assume that it is, otherwise the object backing my NSString*
wouldn't be owned anywhere and would thus be freed automatically (coming from Java land this makes sense as all references are strong by default).
Are there any other modifiers which make sense in this situation, such as copy
or assign
?
Does declaring the property as (readonly,nonatomic,strong)
and (readonly,nonatomic)
make any difference to the code which consumes the property? eg. does declaring it without the strong
keyword cause the object pointer to be stored as __unsafe_unretained
where the strong
property would be stored in a __strong
pointer?
Thanks!
EDIT
So as I understand now, the following applies to readonly properties:
- For non-NSObject* types (int, float, void*, etc) use
(readonly, assign)
.
- For object pointers, use
(readonly, strong)
or (readonly, copy)
- these function the same for readonly properties but you may want the copy semantics if you extend/subclass and redeclare the property as readwrite
.
- For object pointers,
(readonly, weak)
only makes sense if you are going to be storing an already weak pointer in that property (that pointer must be strong elsewhere or the object will be deallocated).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…