Objective-C 运行时:声明符合协议的 Class (objc_class) 类型的变量是什么意思? [英] Objective-C runtime: What does declaring a variable of type Class (objc_class) conforming to a protocol mean?

查看:32
本文介绍了Objective-C 运行时:声明符合协议的 Class (objc_class) 类型的变量是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class bah = [NSString class];

id object = [bah new];

编译完全没有问题.

Class<NSSecureCoding> bah = [NSString class];

id object = [bah new];

返回错误选择器'new'没有已知的类方法".

Returns the error "No known class method for selector 'new'".

为什么第一个实例可以调用NSObject上定义的+new方法,而第二个实例却不能?

Why does the first instance understand that it can call the +new method defined on NSObject but the second instance does not?

推荐答案

根据 Apple 的文档:

According to Apple's documentation:

协议不能用于输入类对象.只有实例可以静态类型到协议,就像只有实例可以静态类型到一个班级.(但是,在运行时,类和实例都响应符合协议:消息.)

Protocols can’t be used to type class objects. Only instances can be statically typed to a protocol, just as only instances can be statically typed to a class. (However, at runtime, both classes and instances respond to a conformsToProtocol: message.)

这是来自旧文档,但没有说它已经改变了.但是假设它仍然有效,基于此,你不应该做你正在做的事情.NSString 的实例可能符合该协议,但您不应该说 NSString Class 对象符合它.

This is from old documentation, but there's nothing saying that it has since changed. But assuming it's still valid, based on that, you shouldn't be doing what you're doing. Instances of NSString may conform to that protocol, but you shouldn't be saying that the NSString Class object conforms to it.

至于它为什么给你错误,我相信是因为当你指定协议时,它会报告不在该协议中的方法的错误.例如,下面给出了一个错误:

As for why it gives you the error, I believe it's because when you're specifying the protocol, it will report an error for methods not in that protocol. For example, the following gives an error:

Class<NSSecureCoding> bah = [NSString class];
id object = [bah class];

但是下面的代码会编译(虽然它会警告class是一个实例方法,而不是一个类方法):

But the following will compile (although it gives a warning that class is an instance method, not a class method):

Class<NSObject> bah = [NSString class];
id object = [bah class];

你还会注意到 new 没有在 NSObject 协议中定义,只在 NSObject 类中定义.

Also you'll notice that new is not defined in the NSObject protocol, only in the NSObject class.

因此,当您只指定 Class 时,编译器似乎会执行与您指定 id 时类似的事情,因为它不知道确切的类型,因此它会让您从任何已知类型调用方法.但是当你向它添加协议时,它只会让你从该协议调用方法.

So when you just specify Class, the compiler appears to do something similar to when you specify id in that it doesn't know the exact type, so it will let you call methods from any known type. But when you add the protocol to it, it will only let you call methods from that protocol.

如果您想确保在使用 Class 时分配给 bah 的任何内容都符合特定协议,则可以使用以下内容:

If you want to ensure that whatever you assign to bah conforms to a particular protocol while just using Class, you could use the following:

if ([bah conformsToProtocol:@protocol(NSSecureCoding)])

这篇关于Objective-C 运行时:声明符合协议的 Class (objc_class) 类型的变量是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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