OC之runtime的(isKindOfClass和isMemberOfClass)
写如下代码:
BOOL flag1 = [[NSObject class] isKindOfClass:[NSObject class]]; BOOL flag2 = [[NSObject class] isMemberOfClass:[NSObject class]]; BOOL flag3 = [[LBPerson class] isKindOfClass:[LBPerson class]]; BOOL flag4 = [[LBPerson class] isMemberOfClass:[LBPerson class]]; NSLog(@"%d %d %d %d", flag1, flag2, flag3, flag4);
打印结果如下:
1 0 0 0
在objc中拿到isKindOfClass和isMemberOfClass的实现代码如下:
+ (BOOL)isMemberOfClass:(Class)cls { return self->ISA() == cls; } - (BOOL)isMemberOfClass:(Class)cls { return [self class] == cls; } + (BOOL)isKindOfClass:(Class)cls { for (Class tcls = self->ISA(); 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; }
观察源码可以看出,isMemeberOfClass类方法取的的消息接收者的父类与后者相比较,是否相等
isKindOfClass类方法会取消息接受者的父类,直到取到NSObject比较,判断的是消息接收者的父类是不是后者的父类或者元类,到NSObject结束
同样的是两者的对象方法取得是接受者的类对象相比较