小编典典

如何测试对象在 Objective-C 中属于哪个类?

all

如何测试对象是否是 Objective-C 中特定类的实例?假设我想查看对象 a 是 b 类还是 c 类的实例,我该怎么做呢?


阅读 129

收藏
2022-06-25

共1个答案

小编典典

要测试 object 是否是类 a 的实例:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.

或者

[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

要获取对象的类名,您可以使用NSStringFromClass函数:

NSString *className = NSStringFromClass([yourObject class]);

或来自objective-c运行时api的c函数:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

编辑: 在斯威夫特

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}
2022-06-25