isMemberOfClass
:对象是否是某类型对象。
isKindOfClass
:对象时否是某类型或类型子类的对象。
isSubclassOfClass
、isAncestorOfObject
:类对象是否是另一个类型的子类、父类。
respondsToSelector
:是否能响应某方法。
conformsToProtocol
:是否遵循某协议。
class
与object_getClass
:
- 实例
class
= object_getClass(self)
- 类
class
返回自身;object_getClass(类对象)
返回元类。
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| // 判断当前对象、类的isa指向是不是类、原类 + (BOOL)isMemberOfClass:(Class)cls { return object_getClass((id)self) == cls; } - (BOOL)isMemberOfClass:(Class)cls { return [self class] == cls; }
// 判断当前对象、类的isa是不是类、元类或者其子类类型 + (BOOL)isKindOfClass:(Class)cls { for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) { if (tcls == cls) return YES; } return NO; } - (BOOL)isKindOfClass:(Class)cls { for (Class tcls = [self class]; tcls; tcls = tcls->superclass) { if (tcls == cls) return YES; } return NO; }
Class object_getClass(id obj) { if (obj) return obj->getIsa(); else return Nil; }
|
显然isKindOfClass
范围更大,当调用对象和参数都是类时,类对象的isa指向元类对象,而其元类的superclass指向class对象,所以满足条件返回YES。所以[instance/class isKindOfClass:[NSObject class]];
都返回 1。
1 2 3 4 5 6 7 8 9 10 11 12
| @interface Person : NSObject @end ...... BOOL res1 = [[NSObject class] isKindOfClass:[NSObject class]]; BOOL res2 = [[NSObject class] isMemberOfClass:[NSObject class]]; BOOL res3 = [[Person class] isKindOfClass:[Person class]]; BOOL res4 = [[Person class] isMemberOfClass:[Person class]];
NSLog(@"%d,%d,%d,%d", res1, res2, res3, res4); ......
// 1,0,0,0
|