In Objective-C, what happens to the original object when the init method sets self?
I have three Objective-C classes:
@interface ClassA : NSObject{
IBOutlet id<ClassAProtocol>delegate
//other instance variables
}
//methods
@end
@interface ClassB : ClassA{
//instance variables
}
//methods
@end
@interface ClassC : ClassA{
//instance variables
}
//methods
@end
My objective is so that when an instance of ClassA
is called for in either code or InterfaceBuilder, an instance of ClassB
or ClassC
is actually created. Whether it will be ClassB
or ClassC
depends on a return value of a method in ClassAProtocol
as implemented by the delegate
object.
@implementation ClassA
static BOOL _initFromSubclass = NO;
-(id)init{
if(_initFromSubclass){
_initFromSubclass = NO;
self = [super init];
}else {
_initFromSubclass = YES;
if([delegate shouldInitClassB]){
self = [[ClassB alloc] init];
}else{
self = [[ClassC alloc] init];
}
}
return self;
}
//other methods
@end
This doesn't work the way I wanted because at the init call, the delegate (set in Interface Builder) is still nil, and so the object created is always ClassC
. Also, a ClassA
object is created first, then, in its init call, creates a new ClassC
object, with a different memory address, and no ClassA
object is dealloced. I have three questions:
1)What happens to the original ClassA
object? (I think it's leaked, but I want to开发者_运维问答 know).
2)How do I avoid the leak?
3)How do I accomplish what I actually want? By the time the delegate is set (say, in awakeFromNib
method), it's too late to reset the object.
Yes I think it will be leaked because it has a retain count of +1 after the
alloc
but nothing will release it.You can use
[self release]
before reassigning the value ofself
. Some argue that it should be[self dealloc]
directly, but I personally prefer the former.Objects instantiated from nibs are sent
initWithCoder:
messages I think, so override that instead ofinit
. Although, at this point, I'm still not sure whetherdelegate
will be set.
精彩评论