单例的实例类型与类名? [英] instancetype vs class name for singleton?

查看:61
本文介绍了单例的实例类型与类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,instancetype 向编译器声明方法的返回类型与接收消息的类相同.

From what I understand, instancetype declares to the compiler that the return type of the method is the same as the class receiving the message.

传统上,我总是将类名显式设置为返回类型来声明我的单例初始值设定项:

Traditionally I've always declared my singleton initializers with the class name explicitly set as the return type:

@interface MyClass : NSObject
+ (MyClass *)sharedInstance;
@end

现在我想知道我是否应该使用 instancetype 来代替,就像这样:

Now I'm wondering if I should use instancetype instead, like so:

@interface MyClass : NSObject
+ (instancetype)sharedInstance;
@end   

最后结果是一样的,我只是想知道这里是否有理由使用一个或另一个?

In the end the result is the same, I'm just wondering if there's a reason to use one or the other here?

推荐答案

instancetype 对于涉及继承的情况很有用.假设您有从 B 类继承的 A 类.B 中返回 B 实例的方法可能之前声明为 id,它在 A 中的覆盖可能返回 A 的一个实例 - 这一切都很好,但编译器不知道.然而,通过使用实例类型,编译器会被告知,当调用 A 实例时,该方法返回一个 A 实例,因此可以提供更好的诊断、代码完成等.

instancetype is useful for situations involving inheritance. Consider you have class A which inherits from class B. A method in B which returns an instance of B may be declared previously as id, its override in A may return an instance of A - which is all good but the compiler has no clue. However by using instance type the compiler is informed that when called on an A instance that the method returns an A instance, and so can give better diagnostics, code completion, etc.

现在在您的示例中,您使用了 MyClass * 而不是 id,因此您已经告诉编译器类型.您还有一个共享实例模型(不是 singleton 模型,因为您可以使用 MyClass 的其他实例),您是否可能定义另一个类继承自 MyClass 并覆盖 sharedInstance 方法?可能不会,但如果你这样做 instancetype 可能有用,否则它什么也得不到.

Now in your example you've used MyClass * rather than id, so you've already told the compiler the type. You also have a shared instance model (not a singleton model as you can other instances of MyClass), are you likely to define another class which inherits from MyClass and overrides the sharedInstance method? Probably not, but if you do instancetype may be of use, otherwise it gains nothing.

这篇关于单例的实例类型与类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆