isKindOf
与isMemberOf
问:最终输出的结果是什么?
BOOL re1 = [(id)[NSObject class] isKindOfClass:[NSObject class]]; //
BOOL re2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]]; //
BOOL re3 = [(id)[Person class] isKindOfClass:[Person class]]; //
BOOL re4 = [(id)[Person class] isMemberOfClass:[Person class]]; //
NSLog(@" re1 :%hhd\n re2 :%hhd\n re3 :%hhd\n re4 :%hhd\n",re1,re2,re3,re4);
BOOL re5 = [(id)[NSObject alloc] isKindOfClass:[NSObject class]]; //
BOOL re6 = [(id)[NSObject alloc] isMemberOfClass:[NSObject class]]; //
BOOL re7 = [(id)[Person alloc] isKindOfClass:[Person class]]; //
BOOL re8 = [(id)[Person alloc] isMemberOfClass:[Person class]]; //
NSLog(@" re5 :%hhd\n re6 :%hhd\n re7 :%hhd\n re8 :%hhd\n",re5,re6,re7,re8);
isKindOfClass
打开objc
源码查看
类方法
当前类的元类(父元类,根元类,根类)是否与cls相等
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = self->ISA(); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
实例方法
判断当前类(父类、根类)是否与cls相等
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
底层实现
类似于
alloc
方法,isKindOfClass直接调用到了objc_opt_isKindOfClass
BOOL
objc_opt_isKindOfClass(id obj, Class otherClass)
{
#if __OBJC2__
if (slowpath(!obj)) return NO;
Class cls = obj->getIsa();
if (fastpath(!cls->hasCustomCore())) {
for (Class tcls = cls; tcls; tcls = tcls->superclass) {
if (tcls == otherClass) return YES;
}
return NO;
}
#endif
return ((BOOL(*)(id, SEL, Class))objc_msgSend)(obj, @selector(isKindOfClass:), otherClass);
}
isMemberOfClass
类方法
判断当前的元类是否与cls相等
+ (BOOL)isMemberOfClass:(Class)cls {
return self->ISA() == cls;
}
实例方法
判断当前类是否与cls相等
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
结果
re1 :1
re2 :0
re3 :0
re4 :0
re5 :1
re6 :1
re7 :1
re8 :1
网友评论