Monday, June 15, 2009

Memory Management: alloc vs. convenience constructor vs. accessor method. What is the difference and which is preferred?

The following simple examples illustrate the contrast between creating a new object using alloc, using a convenience constructor, and using an accessor method.

The first example creates a new string object using alloc: It must therefore be released.

- (void)printHello {
    NSString *string;
    string = [[NSString alloc] initWithString:@"Hello"];
    NSLog(string);
    [string release];
}

The second example creates a new string object using a convenience constructor: There is no additional work to do.

- (void)printHello {
    NSString *string;
    string = [NSString stringWithFormat:@"Hello"];
    NSLog(string);
}

The third example retrieves a string object using an accessor method: As with the convenience constructor, there is no additional work to do.

- (void)printWindowTitle {
    NSString *string;
    string = [myWindow title];
    NSLog(string);
}



According to Apple, using accessor methods is the preferred way to go. "Sometimes it might seem tedious or pedantic, but if you use accessor methods consistently the chances of having problems with memory
management decrease considerably. If you are using retain and release on instance variables throughout your code, you are almost certainly doing the wrong thing."

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html

No comments:

Post a Comment