Home / iPad

Freeing up memory

That's not all you're responsible for. You have to always assume that lowmemory conditions prevail, and that the view controller will need to release its view and any objects associated with the view to free up memory. The viewDidUnload method is the counterpart to viewDidLoad - you use it to relinquish ownership in the view and its objects. Back in Listing 1-2 (in case you missed it at the end), you add the following to it:

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    self.imageView = nil;
    self.fallingWords = nil;
}

You're using the preferred method of relinquishing ownership: using the corresponding accessor method to set the value of the object to nil.

Because the view controller also stores references to views and other objects, it's also responsible for relinquishing ownership of those objects safely in its dealloc method, which is why you add them in Listing 1-2:

- (void)dealloc {
    self.imageView = nil;
    self.fallingWords = nil;
    [super dealloc];
}

An object's dealloc method is invoked indirectly through the release instance method of NSObject. Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object - such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super.

If you're building your application for compatibility with the older version of iOS (2.x), your dealloc method should release each object but should also set the reference to that object to nil before calling super.

[Previous] [Contents]