1

在编写 Objective-C 类时,我使用以下便捷方法结构:

+ (MyClass *) myClass {
    return [[[self alloc] init] autorelease];
}

- (id) init {
    if (self = [super init]) {
        // set-up code here...
    }
    return self;
}

MyClass*便利方法应该指定返回类型而不是有什么理由id?或者该init方法应该指定任一返回类型?

这似乎是 Objective-C 代码中的常见模式。直到现在才真正考虑过。

4

2 回答 2

4

最好的选择是 return instancetype- 一个上下文关键字,可以用作结果类型来表示方法返回相关的结果类型。
查看NSHipster 上的这篇文章。

于 2014-03-20T20:10:37.117 回答
3

我认为instancetype现在建议的方法是:

+ (instancetype) myClass {
    return [[[self alloc] init] autorelease];
}

- (id) init {
    if (self = [super init]) {
        // set-up code here...
    }
    return self;
}
于 2014-03-20T20:11:02.983 回答