When you first start developing for Cocoa (iOS or Mac OS) you quickly learn to follow the standard alloc
, init
, and (eventually) release
cycles:
// Allocate and init NSMutableDictionary *dictionary = [[NSDictionary alloc] init]; // Do something with dictionary // ... // Release [dictionary release];
This is great until you discover the convenience of just doing the following:
// Allocate and init NSMutableDictionary *dictionary = [NSDictionary dictionary]; // Do something with dictionary // …
Let's look inside and see what actually happens:
NSMutableDictionary *dictionary = [[NSDictionary alloc] init]; return [dictionary autorelease];
This approach is called autorelease pools and they are a part of the Automated Reference Counting (ARC) memory management model used by the Cocoa platform.
The ARC compiler will autorelease any object for you, unless it's returned from a method that starts with new
, alloc
, init
, copy
, or mutableCopy
in its name. As before...