Search code examples
iphonememory-managementcore-datapropertiescocoa-design-patterns

Best practice for assigning new objects to retained properties?


I am using Core Data for my iPhone app. My attributes are set with retained properties.

For example, a "number" attribute in a "Thing" entity:

#import <CoreData/CoreData.h>

@interface Thing :  NSManagedObject  
{
}
@property (nonatomic, retain) NSNumber * number;
@end

@implementation Thing 
@dynamic number;
@end

When working with Thing objects in my code, I have been setting the number property like this:

thing.number = [[NSNumber alloc] initWithInteger:1];

However, this creates a memory leak (the new NSNumber object has a retain count that is one higher than desired due to the alloc plus property retain).

Since this is for the iPhone OS, I would like to manage memory myself, so I am choosing to not use autorelease pools (which also has the benefits of better performance and lower maximum memory usage).

  1. I know this pattern works (and it has been discussed in several SO posts already):

    NSNumber *num = [[NSNumber alloc] initWithInteger:1];
    thing.number = num;
    [num release];
    

    This pattern is very clear, but I am not thrilled about the three lines or temporary variable.

  2. I think that this will work as well (but I didn't notice it on any SO posts):

     thing.number = [[NSNumber alloc] initWithInteger:1];
     [thing.number release];
    

    This pattern is less clear, but only requires two lines and does not use a temporary variable.

Question
Are there any other patterns for assigning new objects to retained properties (without using autorelease pools)? What is the best practice here?


Solution

  • Aside from using autorelease pools, these are the only ones that I, for one, have seen. I wouldn't be too wary of autorelease. They work just fine, and this is a case where you'll probably not see any performance difference.

    If you really want to avoid that, however, seems the applicable best practice here is the "Principle of Least Surprise". Since the first idiom is found in most of the example code out there, it seems like you should probably just suck up the extra line for the sake of whoever maintains the code.