[ Team LiB ] |
1.5 Memory ManagementTo properly manage memory, Cocoa provides a reference counting mechanism, supported by the NSObject and NSAutoreleasePool classes. As its name suggests, reference counting maintains a count of how many references there are to an object—indicating how many other objects are interested in keeping the object around. Reference counting is not automatic; the compiler has no way to determine an object's lifetime. Therefore, the following NSObject reference counting methods must be called to indicate the level of interest in an object to the memory management system:
The following set of rules will help you perform accurate reference counting and avoid either leaking memory or prematurely destroying objects:
1.5.1 Retaining Objects in Accessor MethodsAccessor methods require a bit of caution, especially those where an object's instance variables are set. Because an object passed to a set method may already be held, you must be careful about how memory management is performed. Releasing an object before retaining it can lead to unfortunate side effects and can be the source of much frustration. To ensure that memory management is performed correctly, send the autorelease method to an old object reference before replacing it with a new reference. Example 1-8 shows how this rule is applied in the Song class's setTitle: method. Example 1-8. Memory management in accessor methods- (void)setTitle:(NSString *)aTitle { [title autorelease]; title = [aTitle retain]; } Another way to ensure proper memory management and further increase encapsulation is to make a copy of the parameter, as shown in Example 1-9. This ensures that even if a mutable subtype of NSString were given, any modifications to that parameter would not change the contents of the title variable. Example 1-9. Copying a parameter to enforce encapsulation- (void)setTitle:(NSString *)aTitle { [title autorelease]; title = [newTitle copy]; } These practices ensure proper memory management in almost all situations you are likely to encounter. However, some fringe cases require care in handling. For more details, see http://www.stepwise.com/Articles/Technical/2002-06-11.01.html. |
[ Team LiB ] |