respondsToSelector instancesRespondToSelector

来源:互联网 发布:阿里云流量计费标准 编辑:程序博客网 时间:2024/04/30 11:13
要检查一个对象是否支持一个方法,我们可以使用respondsToSelector()函数
除了检查对象是否支持一个特定的方法,我们还可以检查类是否会创建支持一个特定的方法的对象。未来做到这一点,我们使用instancesRespondToSelector()方法
举例:
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; color: #da0021} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; min-height: 16.0px} p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo} p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; color: #c800a1} p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; color: #488287} p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'heiti sc light'; color: #00900c} p.p7 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px menlo; color: #4b0080} span.s1 {color: #7b482c} span.s2 {color: #c800a1} span.s3 {color: #000000} span.s4 {color: #4b0080} span.s5 {font: 14.0px menlo; color: #000000} span.s6 {font: 14.0px menlo} span.s7 {color: #2c5a5d} span.s8 {color: #488287} span.s9 {color: #5200d6} span.apple-tab-span {white-space:pre}

#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 



0 0
原创粉丝点击