May 27, 2014

Fast food objective-c (part 10) : Calling Methods on Nil

In Objective-C, the nil object is the functional equivalent to the NULL pointer in many other languages. The difference is that you can call methods on nil without crashing or throwing an exception. 


This technique used by the frameworks in a number of different ways, but the main thing it means to you right now that you usually don't need to check for nil before calling a method on an object. If you call a method on nil that returns an object, you will get nil as a return value. 
We can also use this to improve our dealloc method slightly:
- (void) dealloc
{
    self.caption = nil;
    self.photographer = nil;
    [super dealloc];
}
This works because when we set nil as an instance variable, the setter just retains nil (which does nothing) and releases the old value. This approach is often better for dealloc because there's no chance of the variable pointing at random data where an object used to be. 
Note that we're using the self.<var> syntax here, which means we're using the setter and picking up the memory management for free. If we just directly set the value like this, there would be a memory leak:
// incorrect. causes a memory leak.
// use self.caption to go through setter
caption = nil;

No comments:

Post a Comment