不忘初心,砥砺前行.
一: isKindOfClass
我们先看看isKindOfClass
这个方法在NSObject.mm文件中是怎么定义的
+ (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;
}
这样看这个方法是不是就比较清晰明了了?
对象方法 : [self class]
获取类对象,判断是否和传入的类相等,如果和传入的cls相等,就返回YES,不相等就去判断父类,如果父类也和传入类不相等就返回NO
类方法: 和对象方法逻辑一样,只不过是通过object_getClass((id)self)
获取到元类对象
举例测试一下:
Person *person = [[Person alloc]init];
SubPerson *subPerson = [[SubPerson alloc]init];
NSLog(@"%d",[person isKindOfClass:[subPerson class]]);//0
NSLog(@"%d",[person isKindOfClass:[Person class]]);//1
NSLog(@"%d",[person isKindOfClass:[NSObject class]]);//1
NSLog(@"%d",[subPerson isKindOfClass:[Person class]]);//1
NSLog(@"%d",[SubPerson isKindOfClass:[Person class]]);//0
NSLog(@"%d",[SubPerson isKindOfClass:[NSObject class]]);//1
Person类继承自NSObject,SubPerson继承自Person
打印结果:0,1,1,1,0,1
二:isMemberOfClass
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
}
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
对象方法: 判断当前类的类对象和传入的类对象是否相等
类方法 : 判断当前类的元类对象和传入的类对象是否相等
NSLog(@"%d",[subPerson isMemberOfClass:[subPerson class]]);//1
NSLog(@"%d",[subPerson isMemberOfClass:[Person class]]);//0
NSLog(@"%d",[subPerson isMemberOfClass:[NSObject class]]);//0
NSLog(@"%d",[person isMemberOfClass:[NSObject class]]);//0
NSLog(@"%d",[Person isMemberOfClass:object_getClass([Person class])]);//1
NSLog(@"%d",[Person isMemberOfClass:[Person class]]);//0