Setting to nil
and releasing are two distinct operations.
You release
an object to relinquish ownership of it. This is covered in the standard Memory Managemange Guidelines. If you are not familiar with them, you should read them before doing any further iOS programming.
After releasing an object, you should set it to nil
if you know that some other code may attempt to access that variable later. This is most common with instance variables.
For example, you may use an instance variable to store some sort of cache:
- (NSArray *)items
{
if (!cachedItems) {
cachedItems = [[self calculateItems] retain];
}
return cachedItems;
}
Later on you may need to clear this cache:
- (void)invalidateCache
{
[cachedItems release];
cachedItems = nil;
}
We need to set cachedItems to nil because our items
method may attempt to use it later. If we do not set it to nil
, messages send to the (now released) cache can lead to a crash.
So set a variable to nil after releasing it when it can potentially be access by other methods in your class at a later point in time.