Objective c instancetype应该用于alloc/new/init方法吗?
根据,当返回Objective c instancetype应该用于alloc/new/init方法吗?,objective-c,clang,instancetype,Objective C,Clang,Instancetype,根据,当返回id的方法是以new或alloc开头的类方法,或以retain、autorelease、init或self开头的实例方法时,隐式地知道该方法返回instancetype 为了保持一致性,这些方法是否也应该在新代码中显式返回instancetype - (instancetype)init { self = [super init]; if (self) { // perform initialization } return self;
id
的方法是以new
或alloc
开头的类方法,或以retain
、autorelease
、init
或self
开头的实例方法时,隐式地知道该方法返回instancetype
为了保持一致性,这些方法是否也应该在新代码中显式返回instancetype
- (instancetype)init {
self = [super init];
if (self) {
// perform initialization
}
return self;
}
是否有任何文件说明原因或原因,或任何推理?在这种情况下,编译器对它的解释似乎完全相同。实际上没有必要这样做,因为编译器会自动将这些方法有效地升级为返回
instancetype
这在llvm文档中有记录
就个人而言?我总是显式地将它们声明为
instancetype
,因为它准确地描述了契约,便于以后进行重构。默认值是“id”,而不是instancetype。返回instancetype可以进行更多的类型检查。如果您的代码是正确的,则没有区别,但是如果您返回id,编译器可能会错过错误。@gnasher729请参阅llvm()中的instancetype文档<对于某些方法,instancetype
是自动推断的,因此,instancetype
是这些情况下的默认值。