源码实现
减号开头的方法
//判断类对象是否是传进来的类对象
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
//判断类对象是否是传进来的类对象类型或者类对象的子类
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
加号开头的方法
//判断类对象的元类是否是传进来的类对象
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
}
//判断类对象的元类 或者类对象的父类的元类 是否是传进来的类对象
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
// 这句代码的方法调用者不管是哪个类(只要是NSObject体系下的),都返回YES
//子类的元类对象通过superClass可以拿到父类的元类对象 一层层往上拿可以拿到基类的元类对象 基类的元类对象superClass指向基类的类对象
NSLog(@"%d", [NSObject isKindOfClass:[NSObject class]]); // 1
NSLog(@"%d", [NSObject isMemberOfClass:[NSObject class]]); // 0
//[类对象 isKindOfClass:];左边类对象的元类是否是右边类
NSLog(@"%d", [Person isKindOfClass:[Person class]]); // 0
//[类对象 isKindOfClass:];左边类对象的元类是否是右边类 或者右边类的父类
NSLog(@"%d", [Person isMemberOfClass:[Person class]]); // 0
NSLog(@"%d", [Person isMemberOfClass:object_getClass([MJPerson class])]); // 1
id person = [[Person alloc] init];
NSLog(@"%d", [person isMemberOfClass:[Person class]]);
NSLog(@"%d", [person isMemberOfClass:[NSObject class]]);
NSLog(@"%d", [person isKindOfClass:[Person class]]);
NSLog(@"%d", [person isKindOfClass:[NSObject class]]);
打印1、0、1、1
网友评论