I’ve been wandering how I can release my retained property in my dealloc method for a long time. For the sake of clearness, here is some sample code:
@interface MyClass: NSObject
{
//...
NSString *myStr;
//...
}
@property (retain, nonatomic) NSString *myStr;
//...
@end
@implementation MyClass
@synthesize myStr;
//...
//version 1 of dealloc
-(void)dealloc
{
[myStr release];
//...
}
//version 2 of dealloc
-(void)dealloc
{
self.myStr = nil;
}
//...
@end
As you can see, in my sample code are two versions of dealloc method. As far as I am concerned, the first one results in less machine code than the second one do and therefore faster. But I once heard that it was a good habit to dispose of the retained property in the second way, that is setting it to nil by calling the setter using self keyword. Can anyone tell me whether these are all true and if so should I stick to the “good habit” or just make my code faster regardless of whatever “good habit”?
Thank you in advance.
If you have the option, the first choice is better because it is less likely to have side effects. But the question of speed is almost certainly irrelevant in any real application. The speed of a property accessor versus
releaseindeallocjust isn’t going to have any noticeable effect on your program. (If nothing else, cost of allocating an object in the first place dwarfs any performance gain you could hope to get by shaving a few message sends off ofdealloc, so if you this were an actual concern, the better approach would be to cut down on allocations.)