문제

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