- Retaining and Releasing
- Assigning to Instance Variables
- Automatic Reference Counting
- Returning Objects via Pointer Arguments
- Avoiding Retain Cycles
- Migrating to ARC
- Autorelease Pools
- Using Autoreleased Constructors
- Autoreleasing Objects in Accessors
- Supporting Automatic Garbage Collection
- Interoperating with C
- Understanding Object Destruction
- Using Weak References
- Allocating Scanned Memory
Autoreleasing Objects in Accessors
From: ivar.m
Another common issue with reference counting, as implemented in Foundation, is that you commonly don’t retain objects that you only reference on the stack. Imagine that you have some code like this:
NSString *oldString = [anObject stringValue]; [anObject setStringValue: newString];
If the -setStringValue: method is implemented as I suggested earlier, this code will crash because the object referenced by oldString will be deleted when you set the new string value. This is a problem. There are two possible solutions, both involving autorelease pools. One is to autorelease the old value when you set the new one. The other is the definition of the -stringValue method from the start of this section.
This ensures that the string will not be accidentally destroyed as a result of anything that the object does. Another common idiom is to substitute a -copy message for -retain. This is useful if the instance variable might be mutable. If it’s immutable, -copy will be equivalent to -retain. If it’s mutable, the caller will get an object that won’t change as a result of other messages sent to the object.