0

I'm getting a leak in initWithCoder method.

Does unarchiveObjectWithData:cacheData return me an autoreleased object? whose responsible to release the object return from unarchiveObjectWithData:cacheData?

@implementation MyObject
@synthesize something = _something;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
         self.something = [aDecoder decodeObjectForKey:@"something"];
    }
}

- (void)dealloc
{
        self.something = nil;
        [super dealloc];
}

@end

This is where i read the object from file

MyObject *myObject = [NSKeyedUnarchiver unarchiveObjectWithData:cacheData];
1
  • 1
    It's been discussed before, but using accessor methods during init and dealloc is discouraged because it can have unintended side-effects. In trivial cases like the above it is not an issue, but in complicated initialisation, observation through KVO, or in complicated object hierarchies it can cause a lot of unintended side-effects. Commented May 9, 2012 at 23:30

1 Answer 1

1

Does unarchiveObjectWithData:cacheData return me an autoreleased object? whose responsible to release the object return from unarchiveObjectWithData:cacheData?

Just remember NARC. If the method you are calling begins with new, alloc, retain, or copy, then you own any object that is returned and have to release it. If it doesn't, then it is autoreleased.

Sign up to request clarification or add additional context in comments.

4 Comments

And thus the returned object is autoreleased.
You shouldn't assume it is autoreleased, you should only assume you don't own it. A lot of methods return objects that you don't own and aren't autoreleased, e.g. [NSFileManager defaultManager] and other singleton types, and also for cached NSNumber etc.
I was guessing that was the answer, so why am I getting a memory leak?
Maybe you have an unbalanced retain elsewhere in your code. You need to track all of the retains and releases through the life of the object and then pair them off to see if they are balanced. Of course, you'd use Instruments to collect the data, but analyzing it is up to you. The other helpful tool is the static analyzer (Build and Analyze).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.