【问题标题】:What should I do with the no-arguments init method if there are not default values?如果没有默认值,我应该如何处理无参数的 init 方法?
【发布时间】:2011-04-17 11:02:30
【问题描述】:

如果我实现了一个没有合理默认值的类,我应该如何处理不带参数的 init 方法?如果没有有效的默认值,则 init 方法没有用。

我的直觉说它应该释放对象并返回 nil:

- (id)init {
    [self release];
    return nil;
}

...但是在读取 NSObject 的 Apple docs 时:

每个类都必须保证 init 方法要么返回该类的完整功能实例,要么引发异常。

这让我很困惑:(

【问题讨论】:

标签: objective-c


【解决方案1】:

引发异常。 :) 像这样:

- (id)init
{
    [self release];
    //self = nil; not required when throwing an exception
    @throw [NSException
        exceptionWithName: NSGenericException
        reason:            @"-init not supported"
        userInfo:          nil];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-02
    • 2017-04-23
    • 2011-03-18
    • 2012-01-16
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多