这两个方法都有实例方法和类方法
实例方法内部:调用者的类对象 == 传进去的 cls
类方法内部:调用者的元类的对象 == 传进去的 cls
源码:
- (BOOL)isKindOfClass:(Class)cls {
// 当前类对象 == cls 或 cls子类
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls)
return YES;
}
return NO;
}
- (BOOL)isMemberOfClass:(Class)cls {
// 当前类对象 == cls
return [self class] == cls
}
+ (BOOL)isKindOfClass:(Class)cls {
// 当前元类对象 == cls 或 cls子类
for (Class tcls = object_getClass(self); tcls; tcls = tcls->superclass) {
if (tcls == cls)
return YES;
}
return NO;
}
+ (BOOL)isMemberOfClass:(Class)cls {
// 当前元类对象 == cls
return object_getClass(self) == cls
}
即:
[对象 isKindOfClass:类对象];
[类对象 isKindOfClass:元类对象];
[对象 isMemberOfClass:类对象];
[类对象 isMemberOfClass:元类对象];
但是,如果 [类对象 isKindOfClass:[NSObject class]]; == YES
因为:子类的元类对象的 superclas->superclass->superclass ... 基类的类对象
面试题
1、以下两组代码的打印结果?
BOOL re1 = [[NSObject class] isKindOfClass:[NSObject class]]; // YES
BOOL re2 = [[NSObject class] isMemberOfClass:[NSObject class]]; // NO
BOOL re3 = [[Person class] isKindOfClass:[Person class]]; // NO
BOOL re4 = [[Person class] isMemberOfClass:[Person class]]; // NO
BOOL re5 = [[NSObject alloc] isKindOfClass:[NSObject class]]; // YES
BOOL re6 = [[NSObject alloc] isMemberOfClass:[NSObject class]]; // YES
BOOL re7 = [[Person alloc] isKindOfClass:[Person class]]; // YES
BOOL re8 = [[Person alloc] isMemberOfClass:[Person class]]; // YES
网友评论