【问题标题】:Should instancetype be used on alloc/new/init methods?应该在 alloc/new/init 方法上使用 instancetype 吗?
【发布时间】:2013-05-30 21:18:04
【问题描述】:

根据clang documentation,当一个以newalloc开头的类方法或以retain开头的实例方法时,隐式知道返回id的方法返回instancetypeautoreleaseinitself

为了一致性,这些方法是否也应该写成在新代码中显式返回instancetype

- (instancetype)init {
    self = [super init];
    if (self) {
        // perform initialization
    }
    return self;
}

是否有任何关于为什么或为什么不的文档,或任何推理?在这种情况下,编译器对它的解释似乎完全相同。

【问题讨论】:

    标签: objective-c clang instancetype


    【解决方案1】:

    实际上没有必要,因为编译器会自动将此类方法提升为有效地返回instancetype(如您所述)。

    这个automatic inference 记录在 llvm 文档中。

    个人?我总是将它们明确声明为instancetype,因为它准确地描述了合同,并且便于以后重构。

    【讨论】:

    • 默认是“id”,不是instancetype。返回 instancetype 为您提供更多类型检查。如果您的代码正确,则没有区别,但如果您返回 id,编译器可能会错过错误。
    • @gasher729 请参阅 llvm (clang.llvm.org/docs/LanguageExtensions.html) 中的实例类型文档。 instancetype 会自动推断为某些方法,因此,instancetype 是这些情况下的默认值。
    猜你喜欢
    • 2010-10-17
    • 2016-01-22
    • 2013-06-12
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    相关资源
    最近更新 更多