Objective-C Difference between setting nil and releasing

14,168

Solution 1

self.object = nil calls your setter, which will release the old value, set the member to nil, and possibly do other things (it's a method, so it could do anything). The "anything" part of that is potentially dangerous; see this question, for example.

[object release] releases the old value, but leaves the member as a now-dangling pointer, which is a good recipe for bugs. In dealloc it doesn't really matter, since the pointer itself is about to go away too, but in any other case it's a very bad idea to release a member without setting it to nil.

(As a sidenote, you should never assume that releasing an object gives it a reference count of 0. It releases your reference, but other objects may still have references to it.)

Solution 2

If you do object = nil without [object release], that might causes memory leaking. If you do [object release] without object = nil afterwards, object becomes dangling pointer as @Jim suggested. self.object = nil is a sugar for setter function call.

Solution 3

If you just release an object, then it will become freed object.

And if you try to perform any sort of operation on freed object then your app crashes. To avoid such accidents, it is always preferred "assign your object to nil after releasing it". Because we all know any operations performed on nil will not be executed :)

Solution 4

If you do [object release], and want to access the object the app simply crash. If you do object = nil, and want to access the object nothing will perform.

The reason is in the [object release], you are attempted to free the object. so its dont have any pointer (no memoty).In the object = nil, you are attempted to assign the object with null pointer. so if u trying to access the object nothing will happen.

Generally we wrote the code as [object release]; object = nil; because if u access the object unexpectedly, the app wont crashed.

Share:
14,168
mk12
Author by

mk12

Updated on June 28, 2022

Comments

  • mk12
    mk12 almost 2 years

    I've learned that in dealloc you do [object release]; but in viewDidUnload (in a UIViewController subclass) you do self.object = nil. What is really the difference because self.object = nil (we're assuming object is a (nonatomic, retain) property) retains nil (which does nothing) and then releases the old value and then the reference count is 0 right?