如何测试Objective-C中的对象属于哪个类? [英] How do I test which class an object is in Objective-C?
本文介绍了如何测试Objective-C中的对象属于哪个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何测试对象是否是Objective-C中特定类的实例?假设我要查看对象a是类b还是类c的实例,我该如何去做呢?
How do I test whether an object is an instance of a particular class in Objective-C? Let's say I want to see if object a is an instance of class b, or class c, how do I go about doing it?
推荐答案
测试对象是否是a类的实例:
To test if object is an instance of class 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
函数:
To get object's class name you can use NSStringFromClass
function:
NSString *className = NSStringFromClass([yourObject class]);
或Objective-C运行时api中的C函数:
or c-function from objective-c runtime api:
#import <objc/runtime.h>
/* ... */
const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);
编辑:在Swift中
if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
这篇关于如何测试Objective-C中的对象属于哪个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文