I basically have this scenario:
//in interface header @property(nonatomic,retain)OtherClass *otherClass; //implementation - (id)initWithOtherClassInstance:(OtherClass*)otherClass { if (self != [super init]) return self; self.otherClass = otherClass; return self; } - (void)dealloc { //Do I need to release otherClass ? [otherClass release]; [super dealloc]; }
I am wondering if I should release an instance variable that was not explicitly allocated, a new one or a copy was called? The memory management guides say that I don’t want to do this, but I worry about self.otherClass = otherClasssaving the instance variable and thus causing a leak when I decide not to release it in the method dealloc.
self.otherClass = otherClass
dealloc
In addition, freeing an instance variable in a method deallocdoes not throw an exception that would be if it were overridden.
Does my reasoning make sense, and what is the best thing to do in this case?
, , . , [foo release] ivar, set setter, . self.otherClass = nil; .
[foo release]
self.otherClass = nil;
, , .
, , , "". .
,
[self setOtherClass:otherClass]
setOtherClass:
- (void) setOtherClass:(OtherClass*)other { [other retain]; [otherClass release]; otherClass = other; }
, , - .
, , dealloc:
- (void) dealloc { [self setOtherClass:nil]; [super dealloc]; }
init . [super init] .
, , self.otherClass , , , . -init, nil dealloc, , , , , .
, -init -dealloc. , , , , KVO dealloc. , , ivar init dealloc.