Memory management rules when using manual reference counting.
suggest changeThese rules apply only if you use manual reference counting!
- You own any object you create
By calling a method whose name begins with alloc, new, copy or mutableCopy. For example:
NSObject *object1 = [[NSObject alloc] init];
NSObject *object2 = [NSObject new];
NSObject *object3 = [object2 copy];
That means you are responsible for releasing these objects when you are done with them.
- You can take ownership of an object using retain
To take ownership of an object, call retain.
NSObject *object = [NSObject new]; // object already has a retain count of 1
[object retain]; // retain count is now 2
This only makes sense in a few situations, such as an accessor or an initializer. Retain the new value before releasing the old one, so assigning the same object does not free it:
- (void)setStringValue:(NSString *)stringValue {
[stringValue retain];
[_privateStringValue release];
_privateStringValue = stringValue;
}
- When you no longer need it, you must relinquish ownership of an object you own
NSObject *object = [NSObject new]; // The retain count is now 1
[object performAction1]; // Done with the object
[object release]; // Release the object
- You must not relinquish ownership of an object you do not own
That means when you didn’t take ownership of an object you don’t release it.
- Autoreleasepool
An autorelease pool releases every object in the pool that received an autorelease message, when the pool drains.
@autoreleasepool {
NSString *string = [NSString stringWithString:@"We don't own this object"];
}
stringWithString: returns an object the caller does not own. A typical implementation owns it briefly, then autoreleases that ownership:
+ (NSString *)stringWithString:(NSString *)string {
NSString *createdString = [[NSString alloc] initWithString:string];
[createdString autorelease];
return createdString;
}
You still need an autorelease pool, because some objects you use are not ones you own (rule 4 does not mean those objects never need to be released). Automatic reference counting applies these rules for you.