class_respondsToSelector 判断某个类是否有某个实例方法,有则返回YES,否则返回NO
/**
* Returns a Boolean value that indicates whether instances of a class respond to a particular selector.
*
* @param cls The class you want to inspect.
* @param sel A selector.
*
* @return \c YES if instances of the class respond to the selector, otherwise \c NO.
*
* @note You should usually use \c NSObject's \c respondsToSelector: or \c instancesRespondToSelector:
* methods instead of this function.
*/
OBJC_EXPORT BOOL class_respondsToSelector(Class cls, SEL sel)
__OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);
测试:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//其中printDZL是Person类的实例方法,printDZ是Person类的类方法
Person * p1 = [[Person alloc] init];
BOOL isOrNot = class_respondsToSelector([p1 class], @selector(printDZL));
BOOL isOrNot2 = class_respondsToSelector([Person class], @selector(printDZ));
NSLog(@"%i--%i", isOrNot, isOrNot2);
}输出:
2015-11-04 13:53:33.019 02-runtime[3053:76771] 1--0

本文介绍如何使用Objective-C的class_respondsToSelector函数来检查类是否响应特定的选择器,即是否实现了一个特定的方法。通过示例代码展示了如何针对实例方法和类方法进行验证。

817

被折叠的 条评论
为什么被折叠?



