ios - "auto"和 "instancetype"类型的主要区别是什么?

标签 ios objective-c

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/

相关文章:

ios - 如何像屏保一样改变CAGradientLayer的颜色?

iphone - 自定义 MKAnnotationView - 如何捕捉触摸而不关闭标注?

iphone - 部署到设备时,带有 iOS 4.2 的 xcode 3.2.5 崩溃

ios - 在 Swift 中分配字符串数组时出错

ios - swift 4 : UIImagePicker delegate methods not being called

ios - 从SQLite提取数据并且只想获取列ID的最后一个值

objective-c - 如何在MenuBar的末尾添加新的Menu?

iphone - NSDateFormatter——没有得到正确的格式化程序字符串

objective-c - 对指向接口(interface) 'NSDate' 的指针进行算术运算,这在非脆弱 ABI 中不是常量大小

objective-c - 如何为任意数量的Lua对象(表)实现(匿名)Lua回调函数?