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];
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • 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. – dreamlax May 09 '12 at 23:30

1 Answers1

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.

Jim
  • 72,985
  • 14
  • 101
  • 108
  • And thus the returned object is autoreleased. – JustSid May 09 '12 at 23:26
  • 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. – dreamlax May 09 '12 at 23:28
  • I was guessing that was the answer, so why am I getting a memory leak? – aryaxt May 09 '12 at 23:28
  • 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). – Ken Thomases May 09 '12 at 23:33