Lets say I have the following code:
@property (nonatomic, retain) *SomeObject foo;
@property (nonatomic, retain) *SomeObject bar;
@synthesize foo, bar;
self.foo = [[SomeObject alloc] init];
self.bar = [[[SomeObject alloc] init] autorelease];
if (self.foo) {
[self.foo release];
self.foo = nil;
}
if (self.bar) {
[self.bar release];
self.bar = nil;
}
I get a memory leak with self.bar. I’m not exactly sure why, but I think it’s because after calling [self.bar release], the object self.bar is pointing to gets autoreleased. When I nil out self.bar, we try to call release on the previous object (which got autoreleased), which creates the error. Is this correct? Also, are there other memory leaks, perhaps with foo?
What would be the correct fix?
Should I remove the release statements and just nil out both properties?
You should just use the accessors directly:
because the synthesized property accessors generate the code to perform reference count operations.
The form
[someObject.someProperty release]should never be used.The only place you should not use the accessors is in partially constructed states (i.e. initialization and
dealloc). In that context, use direct access:[ivar release], ivar = nil;.