Objective-C Property - Difference Between Retain and Assign
I think I am missing something about property attributes.
First, I can't understand the difference between retain
and assign
.
If I use assign
, does the property increase the retain
counter by 1 to the setter and also to the getter, and do I need to use release
to both of them?
And how does this work with readwrite
or copy
? From the view of a retain
count.
I am trying to understand when i need to use release
after working with a property (setter and getter)
@property (readwrite,assign) int iVar;
What does assign
do here?
What is the difference between:
@property (readwrite,assign) int iVar;
and
@property (readwrite,retain) int iVar;
and
@property (readwrite) int iVar;
Many thanks...
what is the different between : @property (readwrite,assign) int iVar; to @property (readwrite,retain) int iVar; to @property (readwrite) int iVar;
The setter for @property (readwrite,assign) sometype aProperty;
is semantically equivalent to
-(void) setAProperty: (sometype) newValue
{
ivar = newValue;
}
The above is more or less what you will get if you put
@asynthesize aProperty = ivar;
in your implementation.
The setter for @property (readwrite,retain) sometype aProperty;
is semantically equivalent to
-(void) setAProperty: (sometype) newValue
{
[newValue retain];
[ivar release];
ivar = newValue;
}
Clearly, it makes no sense to retain or release an int, so sometype must be either id
or SomeObjectiveCClass*
The setter for @property (readwrite,copy) sometype aProperty;
is semantically equivalent to
-(void) setAProperty: (sometype) newValue
{
sometype aCopy = [newValue copy];
[ivar release];
ivar = aCopy;
}
In this case, not only must sometype be an objective C class but it must respond to -copyWithZone:
(or equivalently, implement NSCopying
).
If you omit retain or assign or copy, the default is assign.
By the way, I have simplified the above by not considering the locking that occurs because the properties don't also specify nonatomic
.
There are two kind of specifiers:
The readwrite
specifier tells that the property will be read/write, so when you do a @ synthesize
it will create both the getter and the setter.
There's also readonly
, to specify that the property will only have a getter.
The other modifiers specify how the properties will behave respect of the reference counting:
The assign
modifier, tells that the ivar will simply be assigned with whatever the setter receives. So, in case of an object, retain
won't be called.
With retain
, whenever you use the synthesized setter, retain
will be called, so the object will be retained. This means that the class that has the setter needs to release
it at some point (probably in its dealloc
method).
As for copy
, it means that instead of retain
, the object will receive a copy
message. This means that you'll end up with a copy of the original object, with a retain count of one, so again, you are responsible of releasing it.
精彩评论