【问题标题】:How to override init method to return other class?如何重写 init 方法以返回其他类?
【发布时间】:2014-03-04 03:10:27
【问题描述】:

如何重写 init 方法以返回其他类?像这样

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];

那么,在ARC中,我是否应该关心ClassA的alloc操作呢?

而且,在 NonARC 中,有什么区别?

顺便说一句,使用类方法实现不在讨论中,我只关心如何覆盖init方法以返回其他类?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    您的代码使用 ARC 看起来不错。对于非ARC,你需要释放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];
    }
    

    【讨论】:

    • 对于非arc,只alloc不init,可以吗?
    • @simalone 很好。除非你在 dealloc 中做一些奇怪的事情,这需要 init
    • 有点奇怪,比如什么?
    • @simalone 取消引用指针,在init 中分配。如果不检查可能会导致取消引用空指针错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    相关资源
    最近更新 更多