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).
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.
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?