Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is It Necessary to Set Pointers to nil in Objective-C After release?

Tags:

Is there anything wrong with doing something like

NSString * string = [ [ NSString alloc ] init ];
...
[ string release ];

or is there any value (other than best practice) in also adding

string = nil;

?

like image 294
CIFilter Avatar asked Apr 29 '09 17:04

CIFilter


People also ask

Is it necessary to initialize a pointer?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable.

Is it essential to initialize NULL pointer?

No, you don't have to set it to NULL , but some consider it good practice as it gives a new pointer a value that makes it explicit it's not pointing at anything (yet). If you are creating a pointer and then immediately assigning another value to it, then there's really not much value in setting it to NULL .

Does Objective-C use pointers?

Objective-C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.

What happens when we invoke a method on a nil pointer?

You can validly send any message to a "nil" pointer in Objective-C. This is very different to languages like C++ where invoking a method on a "NULL" pointer will likely crash your program. Sending a message to "nil" will have only one effect: it will return a zero value. No other action will occur.


2 Answers

Not necessary, but good practice. If you were to inadvertently reference it after release, bad things could happen, but in Objective C there isn't any harm in referencing a nil.

like image 85
Paul Tomblin Avatar answered Nov 20 '22 01:11

Paul Tomblin


Setting an instance variable to nil is more useful in a multi-threaded application than a single-threaded one, since with multiple threads you can't always guarantee that an instance variable will only be read before it's released.

I generally don't bother in single-threaded applications, unless there's some other compelling reason.

like image 26
BJ Homer Avatar answered Nov 20 '22 01:11

BJ Homer