I’ve stumbled upon an interesting situation when object could release itself and was wondering what is considered safe and right in this situation.
Imagine we have a class Foo:
@implementation Foo
+ (Foo *) foo {
return [[[Foo alloc] init] autorelease];
}
- (void)resign {
[FooHolder holder].foo = nil;
// here's where the things happen
}
@end
Another class is FooHolder (singleton with one property):
@interface FooHolder : NSObject {
Foo *foo;
}
@property (retain) Foo *foo;
+ (FooHolder *)holder;
@end
And somewhere in the code we do this (calling first stepOne and then stepTwo; autorelease pools are drained after stepOne finishes):
- (void)stepOne {
Foo *foo = [Foo foo];
[FooHolder holder].foo = foo;
}
- (void)stepTwo {
[[FooHolder holder].foo resign]
}
If I’m trying to access self in resign method, after the assignment, with NSZombieEnabled, I’m getting a warning that self is already deallocated. This gives me short WTF moment, but alright, I can live without accessing self at this part. What bothers me more, if object is already deallocated, who can guarantee that stack is not damaged, and we are proceeding normally with our local and instance variables? In general, is it a bad practice to allow self to be deallocated while in the method?
Yes because from the point that self is deallocated all of your ivars could also be deallocated.
I won’t pretend to understand your design or your reasons for doing it but why do you not rearrange your resign method:
You should always release owned objects after there is any chance you will use them in the same way that you call
[super dealloc];at the end of-(void)dealloc