auto 和 clang 类型 instancetype 有什么区别?
我们必须在哪里使用 auto 以及我们必须在哪里使用 instancetype

最佳答案

Objective C 中的 auto 继承自 C,表示 auto keyword



如果您正在寻找 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/

10-08 20:49