- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
- 判断当前对象是否是cls类,或者是否是cls的子类的类型
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
- 判断当前类的元类对象是否是cls,如果要为YES,则cls必须传入元类对象
+ (BOOL)isMemberOfClass:(Class)cls {
// object_getClass((id)self)为self的元类对象
return object_getClass((id)self) == cls;
}
- 判断当前类的元类对象是否是cls或者是否是cls的子类,如果要为YES,则cls必须传入元类对象
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 等价于 [NSObjectisKindOfClass:[NSObject class]]);
NSLog(@"%d", [[NSObject class] isKindOfClass:[NSObject class]]); // 1
NSLog(@"%d", [[NSObject class] isMemberOfClass:[NSObject class]]); // 0
NSLog(@"%d", [[MJPerson class] isKindOfClass:[MJPerson class]]); // 0
NSLog(@"%d", [[MJPerson class] isMemberOfClass:[MJPerson class]]); // 0
// 这句代码的方法调用者不管是哪个类(只要是NSObject体系下的),都返回YES, 为元类对象的superclass指向的是类对象
NSLog(@"%d", [NSObject isKindOfClass:[NSObject class]]); // 1
NSLog(@"%d", [NSObject isMemberOfClass:[NSObject class]]); // 0
NSLog(@"%d", [MJPerson isKindOfClass:[MJPerson class]]); // 0
NSLog(@"%d", [MJPerson isMemberOfClass:[MJPerson class]]); // 0
id person = [[MJPerson alloc] init];
NSLog(@"%d", [person isMemberOfClass:[MJPerson class]]); // 1
NSLog(@"%d", [person isMemberOfClass:[NSObject class]]); // 0
NSLog(@"%d", [person isKindOfClass:[MJPerson class]]); // 1
NSLog(@"%d", [person isKindOfClass:[NSObject class]]); // 1
NSLog(@"%d", [MJPerson isMemberOfClass:object_getClass([MJPerson class])]); // 1
NSLog(@"%d", [MJPerson isKindOfClass:object_getClass([NSObject class])]); // 1
NSLog(@"%d", [MJPerson isKindOfClass:[NSObject class]]);// 1
}
return 0;
}
网友评论