蘋果的開源代碼
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
}
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
+ (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;
}
object_getClass() 和class 說明
1.
class
方法返回對象的類對象
2.object_getClass()
函數(shù),就是返回這個對象的isa指針指向的對象
(對象為實例對象則isa指針指向類對象师郑,對象為類對象則isa指針指向元類對象格侯。)
所以我們不難看出
isMemberOfClass:(Class)aClass;
方法的本質(zhì)啊易,就是判斷左邊對象的isa指針指向的對象與右邊對象是否相等瑟啃。
isKindOfClass:(Class)cls
方法的本質(zhì)就是判斷左邊對象的isa指針指向的對象或者isa指向?qū)ο蟮母割?code>superClass是否與右邊的對象相等
面試題:輸出打印結(jié)果
@interface HPPeople : NSObject
@end
@implementation HPPeople
@end
@interface HPStudent : NSObject
@end
@implementation HPStudent
-(instancetype)init
{
if (self = [super init]) {
BOOL res1 = [[NSObject class] isKindOfClass:[NSObject class]];
BOOL res2 = [[NSObject class] isMemberOfClass:[NSObject class]];
BOOL res3 = [[HPPeople class] isKindOfClass:[NSObject class]];
BOOL res4 = [[HPStudent class] isMemberOfClass:[NSObject class]];
NSLog(@"%d,%d,%d,%d",res1,res2,res3,res4);
}
return self;
}
@end
正確輸出為:1,0啥供,0稠集,0
首先判斷res2和res4 左邊類對象的isa指針指向元類對象MetaClass
奶段,元類對象MetaClass
與右邊的類對象明顯不相等返回 NO,res3中HPPeople
的元類對象MetaClass
及他的父類superClass
明顯也不等于NSObjec
的類對象故res3返回NO.
看到這里似乎res1也應(yīng)該返回NO剥纷,但事實總是打臉痹籍,res1返回的是Yes。原因是NSObject
的元類對象MetaClass
的父類superClass
就是[NSObject class]
而isKindofClass
只要是滿足左邊的對象的isa指向的對象的superClass
等于右邊的對象就會返回Yes