Monday, September 13, 2010

nil, NULL, and release

Just a quick note about how to check whether an object is null or not in Objective-C. In java, it is easy to do that through 'null' keyword. While in Objective-C, there are two keywords, 'NULL' and 'nil', to deal with that action. What is the difference? NOTHING. Both keywords point to __DARWIN_NULL which is defined as : #define NULL ((void *)0) . It means, they point to address 0 in memory.

When we release an object using [object release], don't forget to set it to nil or NULL because when we compare it in 'if' statement, it won't be true because it is still pointing to its old address.

For example:

MyViewController c = [[MyViewController alloc] init];
[c release];

If we compare it in 'if' statement if(c), the statement will return true because the pointer is still pointing to its address even tough we have released it before. We need to set it to nil or NULL c = nil to make it point to address 0. After we do that, if(c) will return 0, which is false in C.
 

©2009 Stay the Same | by TNB