这是非常高级的东西。我正在处理一些运行时代码作为一个副项目。我要解决的问题是:如果我有一个类型为 id 的对象,并且该对象可以是字符串、类或协议(protocol),我如何辨别它是什么?
例如,这是我正在处理的一些代码:
[objArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSString class]]) {
// Do something with the string ...
} else if (... obj is a Protocol ...) {
// Do something with the protocol ...
} else if (... obj is a Class ...) {
// Do something with the class ...
} else {
// It's something we are not interested in!
}
}];
到目前为止,我在数组中存储各种 NSString、Class 和 Protocol 实例时没有遇到任何问题,其他一切都很好。我需要检测它们的原因很简单,我无法控制这段代码中的内容。因此,我需要先确定循环正在处理的 obj
是什么,然后再对其进行操作。
我一直在尝试各种运行时函数和东西,但到目前为止,如果确定对象是什么,我运气不好。
有人试过这样的事情吗?
最佳答案
因为 Protocol 是 NSObject 的子类,您可以像检测任何其他类一样检测它。有趣的是,Protocol 类没有公共(public)接口(interface)。
id 类型的对象要么是类,要么是类的实例,所以我会先测试它是否是类,如果失败,则它是类的实例,因此使用字符串比较来确定类名。对于 Protocol 与@"Protocol"
比较例子-
// assign the object to inspect
id obj = //...
NSString *className;
// test for Class type first
if (object_isClass(obj)) {
// it's a Class... inspect further...
className = NSStringFromClass(obj);
if ([className isEqualToString:@"Protocol"]) { /* Protocol Class */ }
}
else {
// must be an instance - get the class name
className = NSStringFromClass([obj class]);
// test for instance of Protocol class
if ([className isEqualToString:@"Protocol"]) { /* Protocol instance */ }
// continue testing for any other classes here...
}
NSStringFromClass 位于 Foundation Functions Reference 中
关于iOS:如何判断类型为 id 的对象是类还是协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432772/