auto
和 clang 类型 instancetype
有什么区别?
我们必须在哪里使用 auto
以及在哪里必须使用 user instancetype
?
最佳答案
Objective C 中的
auto
继承自 C,表示 auto keyword
Defines a local variable as having a local lifetime.
Keyword auto uses the following syntax:
[auto] data-definition; As the local lifetime is the default for local variables, auto keyword is extremely rarely used.
Note: GNU C extends auto keyword to allow forward declaration of nested functions.
如果您正在寻找 C++11 的 auto
或 C# 的 var
的等效项 - 在 Objective C 中使用 id
。
id a = [NSString new];
id b = [NSNumber new];
但是 id
并没有像 C++11 中的 auto
那样在编译时解析为具体类型。
instancetype
是一个上下文关键字,可用作结果类型以表示方法返回相关结果类型。例如:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
instancetype与 id 不同,只能用作方法声明中的结果类型。
使用 instancetype,编译器将正确推断 +personWithName: 的结果是一个 Person 的实例。如果您尝试调用,将会产生错误
[[Person personWithName:@"Some Name"] methodThatNotExistsInPerson];
如果你将使用 id
编译器不会这样做,你不会修复它并且会收到运行时错误!
Instancetype 用于为 Objective C 添加更多的“强类型”。
关于ios - "auto"和 "instancetype"类型的主要区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061741/