On 08/09/2009, at 7:53 AM, DKJ wrote:

- (id)initWithCoder:(NSCoder *)aDecoder
{
        self = [super init];
        theData = [[aDecoder decodeObjectForKey:@"theData"] retain];
        return self;
}

This is how I read the object from disk:

MyObject *myob = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];

(Garbage collection is not activated.) My understanding of the memory management rules is that I don't need to release myob. And I get EXC_BAD_ACCESS errors when I do.

But Instruments is complaining about a memory leak, and mentions NSKeyedUnarchiver. The "retain" message in the initWithCoder makes me wonder.

Is this code leaking? Should I add an autorelease to the retain in initWithCoder?


Yes, you could keep guessing, making wild stabs in the dark without really understanding it until it seems to work. Or you could get your nose into the documentation and work it out ;-)

Your initWithCoder method is fine, assuming of course that you release 'theData' in your dealloc method. Hint: make 'theData' a retained property and it becomes much easier to manage.

The problem is in the other line you posted. [NSKeyedUnarchiver unarchiveObjectWithData:] does not contain the word 'alloc', 'new' or 'copy' therefore you do not own the object it returns. If you'd like to, you need to retain it, and that would later be balanced by a - release when you are no longer interested in it. Releasing without a retain is an over-release and will cause the EXC_BAD_ACCESS.

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to