Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c instancetype应该用于alloc/new/init方法吗?_Objective C_Clang_Instancetype - Fatal编程技术网

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
是这些情况下的默认值。