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;
?
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.
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With