先看看这两个成员方法的苹果官方解释:
-
1、
- (BOOL)isKindOfClass:(Class)aClass
Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class. (required)
这个方法用来判断一个对象是否是指定类或者某个从该类继承类的实例对象。 -
2、
- (BOOL)isMemberOfClass:(Class)aClass
Returns a Boolean value that indicates whether the receiver is an instance of a given class. (required)
这个方法用来判断一个对象是否是指定类的实例对象。两者区别:
isKindOfClass
可以判断某对象是否是某个类的实例对象,这个类和这个类的继承类都可以判断;
而isMemberOfClass
只能判断对象是否是当前类的实例对象。
相信大多数开发者对上面两个成员方法没有太大疑问,那么再来看一下这两个的类方法的底层实现。
- 1、
+ (BOOL)isKindOfClass:(Class)aClass
底层实现:
那么,就等同于+ (BOOL)isKindOfClass:(Class)cls { //取到的是元类 for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) { if (tcls == cls) return YES; } return NO; }
结论:只有/** * Returns YES if aClass is the NSObject class */ + (BOOL)isKindOfClass: (Class)aClass { if (aClass == [NSObject class]) return YES; return NO; }
[[NSObject class] isKindOfClass: [NSObject class]];
为真,[[UIViewController class]isKindOfClass:[UIViewController class]];
为假。
- 2、
+ (BOOL)isMemberOfClass:(Class)aClass
底层实现:相较于+ (BOOL)isKindOfClass: (Class)aClass
少个循环。
所以,这个会一直返回NO。+ (BOOL)isMemberOfClass:(Class)cls { return object_getClass((id)self) == cls; }
将这四种情况以代码的形式说明以下:
BOOL res1 = [[NSObject class] isKindOfClass:[NSObject class]];//1
BOOL res2 = [[NSObject class] isMemberOfClass:[NSObject class]];//0
BOOL res3 = [[Person class] isKindOfClass:[Person class]];//0
BOOL res4 = [[Person class] isMemberOfClass:[Person class]];//0
BOOL res5 = [[NSObject new] isKindOfClass:[NSObject class]];//1
BOOL res6 = [[NSObject new] isMemberOfClass:[NSObject class]];//1
BOOL res7 = [[Person new] isKindOfClass:[Person class]];//1
BOOL res8 = [[Person new] isMemberOfClass:[Person class]];//1
最后,附上isa和superclass总结。