![](/img/trans.png)
[英]What's the main difference between ReactiveCocoa and PromiseKit?
[英]What is main difference between “auto” and “instancetype” type?
auto
和clang类型instancetype
什么区别?
我们必须使用auto
和用户instancetype
?
Objective C中的auto
继承自C,表示auto关键字
将局部变量定义为具有本地生存期。
关键字auto使用以下语法:
[auto]数据定义; 由于本地生存期是局部变量的默认值,因此极少使用auto关键字。
注意:GNU C扩展auto关键字以允许嵌套函数的前向声明。
如果您正在寻找C ++ 11的auto
或C#的var
-in的等价物,则使用Objective C id
。
id a = [NSString new];
id b = [NSNumber new];
但是在编译时, id
没有像c ++ 11中的auto
一样解析为具体类型。
instancetype
是一个上下文关键字,可用作结果类型,表示方法返回相关的结果类型。 例如:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
与id不同, instancetype只能用作方法声明中的结果类型。
使用instancetype,编译器将正确地推断出+ personWithName:的结果是Person的实例。 如果你试图打电话会产生错误
[[Person personWithName:@"Some Name"] methodThatNotExistsInPerson];
如果您将使用id
编译器不会这样做,您将无法修复它并将收到运行时错误!
Instancetype用于为Objective C添加更多“强类型”。
如果你的意思是auto
他们是无关的。
auto
是C99存储类。 存储类定义变量和函数的范围和可见性。 auto
是没有说明符的局部变量的默认值。 其他是extern
, register
, static
。 Objective-C也有__block
,而C11有_Thread_local
。 instancetype
表示返回类型是
id
,LLVM将检测不同类型之间的错误分配。 在构造函数和静态初始化器中使用它。 1接收类是一个更好的术语,因为子类不需要重新定义instancetype
以使其返回子类类型。
正如其他人所说, auto
是一个很少使用的关键字,忘了它。
instancetype
是最近的一个介绍,它允许方法遵循init
模式。 在以init
开头的Objective-C方法中,返回一个类型为接收类的对象 - 换句话说,该方法中的self
类型。 据说init
方法具有相关的结果类型 。 考虑:
@interface A : NSObject
- (id) initWithString:(NSString *)text;
@end
@interface B : A
@end
那么表达式:
[[A alloc] initWithString:@"An instance of A"]
编译器知道结果的类型是A *
而不是为initWithString:
声明的不太具体的id
initWithString:
因为initX
方法具有相关的结果类型。
表达的更多内容:
[[B alloc] initWithString:@"An instance of B"]
编译器知道结果的类型是B *
,好像调用的方法来自A
类(通过继承),它在B
的实例上调用。
instancetype
的引入允许其他方法声明它们遵循这种模式,从而为编译器提供更精确的类型信息 - 例如,它可以用来解析属性引用。 考虑:
@interface A : NSObject
// returns an instance of A or whatever subtype of A it is called on
+ (instancetype) locateWithString:(NSString *)text;
@end
@interface B : A
@property NSInteger size;
@end
表达式:
[B locateWithString:@"An instance of B"].size
编译器知道locateWithString:
返回一个B *
,因此具有属性size
。 之前instancetype
类型id
将不得不被使用,并且类型id
没有财产size
,因此编译器将产生一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.