views:

137

answers:

2

Hi all,

I often see when we release ab object we immediately set it to nil. I know that release and nil both free the old value associated with object but in case of release it leaves the object as a dangling pointer so we have to set it to nil.

So my question is if nil frees the old value of the object and set the object to nil why should not we only use nil why w should use release too.

Way1:

MyClass *obj = [[MyClass alloc] init];

[obj release];

obj = nil;

Way2:

MyClass *obj = [[MyClass alloc] init];

obj = nil;

What is the real difference in way1 and way2 if use way1 why dont use way2 only.

+10  A: 

Setting a pointer to nil does not release the memory occupied by the former destination of that pointer. In plain english, assigning it to nil does not release it.

If your application is garbage collected, release is a no-op and can be left out. Otherwise, it's very, very necessary. Hence, Way 1 is always correct, and Way 2 is correct only under garbage collection.

BJ Homer
There is a notable exception here: **If** it is an instance variable **and** it has been declared as `@property (retain)` **and** you have `@synthesized` the accessors, then those accessor methods will take care of retaining and releasing the objects you assign to them. Of course, this only works if you use the accessor methods: `[self setObj:nil]` or `self.obj = nil` (in objc-2.0).
Matt B.
+1  A: 

It's as BJ said setting it to nil won't free up the memory, and in a non-gc collected environment would cause a memory leak. An alternative that'd possibly be valid as well would be

MyClass *obj = [[[MyClass alloc] init] autorelease];  

obj = nil;
Bryan McLemore