Calling property's setter method with nil value
Co开发者_运维知识库nsider I have a property named sampleObject.
In dealloc method, which should be the best way to manage memory?
Option 1:
self.sampleObject = nil; //This will release the sampleObject and set it to nil
This is equivalent to
[sampleObject release];
sampleObject = nil;
Option 2:
Explicitly releasing an object and setting it to nil
[sampleObject release];
sampleObject = nil;
In my opinion, both would achieve the same results? Please Share your views.
Regards, Krishnan
In the 'dealloc' method you should 'release' the ivar directly and set it to nil.
You do so directly because that avoids executing any custom setter code that may exist in a subclass.
The setting to nil isn't strictly necessary, but it costs virtually nothing to do and you'll be happy you did so during debugging in that it eliminates a dangling pointer.
in a dealloc method, the class is never used again so setting retained resources/properties to nil is just not required. Sending release is the best option and avoids unnecessary code.
Going through the property setter does have a small overhead over directly sending the release
message. Thus, for synthesized properties, it's better to send release
.
Of course, there are cases where you have to call the property setter, if the setter logic is more complex (for example, the property is backed by multiple variables and the setter decomposes the value and cleans up the old one). This is not as common scenario, though.
And since you are deallocating your object, there's no need to set the backing variable explicitly to nil
after you release it.
精彩评论