问题描述
有人可以向我解释(简单来说)为什么在Objective-C中使用 instancetype
?
Can someone please explain to me (in simple terms) why an instancetype
is used in Objective-C?
- (instancetype) init {
self = [super init];
if (self) {
// Custom initialization
}
return self;
}
推荐答案
这是为了提高类型安全性。
过去,初始化者只返回了类型为 id
(任何对象)的对象。
It's to increase type safety.
Back in the old days, initialisers just returned an object of type id
(any object).
使用普通的初始化程序(以init,alloc或new开头的那些),这通常不是问题。编译器会自动推断它返回的类型,因此将对象的任何方法调用都限制为该类的实例方法。
With normal initialisers (those that begin with "init", "alloc" or "new"), this wasn't usually a problem. The compiler would automatically infer the type that it returned and therefore restrict any method calls on the object to the instance methods of that class.
但是,这个是静态便利初始化程序或工厂方法的问题不一定遵循相同的命名约定 - 因此它无法应用相同的类型安全性。
However, this was a problem with static convenience initialisers or "factory methods" that didn't necessarily follow the same naming convention - therefore it was unable to apply the same type safety.
这意味着使用这样的类:
@interface Foo : NSObject
+(id) aConvenienceInit;
@end
编译器会接受这样的代码:
NSArray* subviews = [Foo aConvenienceInit].subviews;
为什么?因为返回的对象可能是任何对象,所以如果你尝试访问 UIView
属性 - 没有类型安全可以阻止你。
Why? Because the returned object could be any object, so if you try and access a UIView
property - there's no type safety to stop you.
但是,现在使用 instancetype
,您获得的结果是您给定实例的类型。现在使用以下代码:
However, now with instancetype
, the result you get back is of type of your given instance. Now with this code:
@interface Foo : NSObject
+(instancetype) aConvenienceInit;
@end
...
NSArray* subviews = [Foo aConvenienceInit].subviews;
您将收到编译器警告,说明该属性子视图
不是 Foo *
的成员:
You'll get a compiler warning saying that the property subviews
is not a member of Foo*
:
虽然值得注意的是编译器会自动转换返回类型从 id
到 instancetype
如果您的方法以alloc,init或new开头 - 但是尽管如此,只要你能使用 instancetype
,这是一个很好的习惯。
Although it's worth noting that the compiler will automatically convert the return type from id
to instancetype
if your method begins with "alloc", "init" or "new" - but nonetheless using instancetype
wherever you can is a good habit to get into.
请参阅了解详情。
这篇关于为什么使用instancetype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!