Why should we let out?

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

So my question is that nil frees the old value of the object and sets the object to nil, why we should not use only nil, why w should also use release.

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 way1 is used Why don't you use way2 only?

+6
memory-management iphone cocoa-touch xcode
source share
2 answers

Setting the pointer to nil does not free the memory occupied by the previous destination of this pointer. In simple English, assigning it to a nile does not liberate.

If your application for garbage collection, the release is no-op and may be omitted. Otherwise, it is very, very necessary. Therefore, path 1 is always correct, and path 2 is correct only for garbage collection.

Note This answer does not apply to projects using automatic reference counting. In ARC, setting the pointer to nil sends the release to the object.

+11
source share

As stated in BJ, setting it to zero will not free up memory, and in an environment not related to gc, it can cause a memory leak. An alternative that could be valid would also be

 MyClass *obj = [[[MyClass alloc] init] autorelease]; obj = nil; 
+1
source share

All Articles