要检查一个对象是否支持一个方法,我们可以使用respondsToSelector()函数
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface Class1 : NSObject
{
}
-(void)print;
@end
@implementation Class1
-(void)print
{
printf("This is Class 1./n");
}
@end
int main (int argc, const char * argv[]) {
Class1 *c1=[Class1 new];
//验证对象支持一个方法
if ([c1 respondsToSelector: @selector(print)]==YES) {
printf("c1 has a print method. /n");
}
//验证类是否创建支持一个特定方法的对象
if ([Class1 instancesRespondToSelector: @selector(print)]==YES) {
printf("Class1 object have a print method /n/n");
}
return 0;
}
输出结果:
c1 has a print method.
Class1 object have a print method
本文介绍如何使用Objective-C的respondsToSelector()和instancesRespondToSelector()方法来检查对象或类是否支持特定的方法。通过示例代码展示了如何验证Class1类的对象是否支持print方法。
58

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



