iOS initWithCoder/decodeObjectForKey memory leak
The Leaks instrument tells me that I have a memory leak when I use decodeObjectForKey
within initWithCoder
. For example:
Class.h
{
MyObject *myObject;
}
@property (nonatomic, retain) MyObject *myObject;
Class.m
@synthesize myObject
-(void)dealloc{
[myObject release];
[super release];
}
-(id)initWithCoder:(NSCoder *)decoder{
if (self = [super init]{
self.myObject = [decoder decodeObjectForKey:@"MyObject"];
}
return self;
}
Per request in the comments:
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:myObject forKey:@"MyObject"];
}
Leaks reports a leak of type NSCFString on the line;
self.myObject = [decoder decodeObjectForKey:@"MyObject];
As I understand it, decodeObjectForKey returns an autoreleased object. Since I immediately assign that value to the myObject property, which is 开发者_开发知识库specified as (nontoxic, retain) in the property definition, I retain the autoreleased object through the setter method of the myObject property. The myObject is then released in the dealloc method. I don't understand where the leak is if I understand the sequence correctly. Also why is it reported as a NSCFString when the type is MYObject?
Any thoughts would be appreciated, including if my assumptions above are correct.
Look carefully at your -dealloc
method. You are calling [super release];
when you should be calling [super dealloc];
.
Calling [super release]
in this case is the same thing as calling [self release]
, since you're not overriding the -release
method. If your -dealloc
method is called, your object has already been fully released, so this is unnecessary. Since you are overriding the -dealloc
method, you must call [super dealloc]
to also free any memory allocated by the superclass.
You can refer to the NSObject documentation to see how to override dealloc correctly.
精彩评论