ObjC类对象可以符合协议吗? [英] Can an ObjC class object conform to a protocol?

查看:65
本文介绍了ObjC类对象可以符合协议吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以告诉编译器类对象符合协议?

Is there a way to indicate to the compiler that a class object conforms to a protocol?

据我所知,通过创建 +( void)foo 类方法,该类对象的实例将具有这些方法作为 instance方法。因此,只要我为所有必需的协议方法创建 +(void)foo 方法,我就可以让一个类对象充当委托。

As I understand, by creating +(void)foo class methods, an instance of that class object will have those methods as instance methods. So, as long as I create +(void)foo methods for all required protocol methods, I can have a class object act as a delegate.

我的问题当然是在类的头文件中,我只知道如何指示类的实例符合协议(通常是这样)。因此,我发现最好的方法就是像这样转换类对象:

My problem of course is that in the class's header file, I only know how to indicate that instances of the class conform to the protocol (as is typically the case). So, the best I've figured out is to cast the class object like so:

something.delegate = (id<SomethingDelegate>)[self class]

有什么想法吗?

相关但不同:
ObjC:是否有类协议之类的东西?

推荐答案

您现在正在做什么是正确的,因为它将使警告静音,这是您的目标。您将为实例发送协议中定义的类对象消息,这有点令人困惑,但是运行时无关紧要。

What you're doing now is correct as it will silence warnings which is your goal. You will be sending the class object messages defined in the protocol for instances which is a bit confusing, but the runtime doesn't care.

这样考虑:您想要将委托设置为一个对象,该对象响应协议中定义的消息。您的班级会这样做,并且您的班级也是一个对象。因此,您应该将您的类视为符合该协议的对象。因此,您所写的内容是完全正确的(基于您要执行的操作)。

Think about it this way: you want to set a delegate to an object that responds to the messages defined in the protocol. Your class does this, and your class is also an object. Therefore, you should treat your class like an object that conforms to that protocol. Therefore, what you've written is completely correct (based on what you're trying to do).

不过要注意的一点是,该类不会正确响应 conformsToProtocol:。无论如何,这对于委托设置通常是可以的(代表通常不检查类是否符合—他们只是检查它是否可以响应选择器)。

One thing to note, though, is this class will not properly respond to conformsToProtocol:. This is generally okay for a delegate setup anyway (delegates don't usually check if the class conforms — they just check if it can respond to a selector).

附带说明,您可以在语法上做的一件事是:

As a side note, one thing you can do syntactically is:

Class<SomethingDelegate> variable = (Class<SomethingDelegate>)[self class];

此处的区别在于,编译器将使用协议中的类方法而不是实例消息。不过,这不是您要的情况。

The difference here is that the compiler will use the class methods from the protocol instead of instance messages. This is not what you want in your case, though.

这篇关于ObjC类对象可以符合协议吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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