How to override init method to return other class? Like this

ClassA.m

- (id)initWithType:(int)type{
    if(type == 0){
        return [[ClassB alloc] init];
    }
    else if(type == 1){
        return [[ClassC alloc] init];
    }

    return [self init];
}

id classInstance = [[ClassA alloc] initWithType:someType];

So, in ARC, if I should care about the alloc operation of ClassA?

And, in NonARC, what's the difference?

BTW, Using class method to implement is not in discussion, I only care about how to override init method to return other class?

有帮助吗?

解决方案

your code looks fine with ARC. for non-ARC, you need to release self

- (id)initWithType:(int)type{
    if(type == 0){
        [self release]; self = nil;
        return [[ClassB alloc] init];
    }
    else if(type == 1){
        [self release]; self = nil;
        return [[ClassC alloc] init];
    }

    return [self init];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top