1.判断类型
isKindOfClass:判断某个对象是否是类的实例对象,或者子类的实例对象
格式:[对象 isKindOfClass:类对象]
BOOL isInstance = [ani isKindOfClass:[Animal class]];
NSLog(@"%d",isInstance); //1 ani 是Animal类的实例
Dog *dog = [Dog new];
isInstance = [dog isKindOfClass:[Animal class]]
NSLog(@"%d",isInstance); //1 dog 是Animal子类Dog类的实例,所以是1
Person *p = [Person new];
isInstance = [p isKindOfClass:[Animal class]];
NSLog(@"%d",isInstance); //0 p 不是Animal类的实例 Person继承自NSObject
2.判断实例
isMemberOfClass:判断对象是否为指定类的实例对象
格式:[对象 isMemberOfClass:类对象]
BOOL isInstance = [dog isMemberOfClass:[Animal class]];
NSLog(@"%d",isInstance); //0, dog不是Animal的实例对象
isInstance = [ani isMemberOfClass:[Animal class]];
NSLog(@"%d",isInstance); //1, ani是Animal的实例对象
isInstance = [p isMemberOfClass:[Person class]];
NSLog(@"%d",isInstance); //1, p是Person的实例对象
3.判断子类
isSubclassOfClass:判断类是否为指定类的子类(类和类之间的关系)
BOOL isSub = [Dog isSubclassOfClass:[Animal class]];
NSLog(@"%d",isInstance); //1, Dog是Animal的子类
isSub = [Dog isSubclassOfClass:[NSObject class]];
NSLog(@"%d",isInstance); //1, Dog是NSObject的子类
isSub = [Person isSubclassOfClass:[NSObject class]];
NSLog(@"%d",isInstance); //1, Dog是Animal的子类
4.检测对象方法响应
respondsToSelector:判断是否恩能响应方法。
//Animal里面只有run方法,Dog里面有test方法
Animal *ani = [Dog new];
[ani test]; //可行
Animal *ani2 = [Animal new];
[(Dog)ani2 test]; //编译不会出错,但会出现运行时错误
SEL s1 = @selector(test); //把test包装成SEL类型
BOOL canResponds = [ani respondsToSelector:S1];
NSLog(@"%d",canResponds); //0 ani无法响应test方法
5.检测类方法响应
instanceRespondToSelector:判断类是否有这个方法。此方法为类方法,不能用在类的对象
SEL s1 = @selector(test);
BOOL isRespond = [Dog instanceRespondToSelector:s1];
NSLog(@"%d",isResponds); //1 Dog类中有test方法
s1 = @selector(run);
isRespond = [Dog instanceRespondToSelector:s1];
NSLog(@"%d",isResponds); //1 Dog类中有run方法,从Animal类继承而来的
|
|