isMemberOfClass | isKindOfClass
1 - 猜想以下代码输出的结果
1 #import <Foundation/Foundation.h> 2 #import <objc/runtime.h> 3 @interface Person : NSObject 4 5 @end 6 @implementation Person 7 8 @end 9 10 int main(int argc, const char * argv[]) { 11 @autoreleasepool { 12 13 NSLog(@"%d", [[NSObject class] isKindOfClass:[NSObject class]]); 14 NSLog(@"%d", [[NSObject class] isMemberOfClass:[NSObject class]]); 15 NSLog(@"%d", [[Person class] isKindOfClass:[Person class]]); 16 NSLog(@"%d", [[Person class] isMemberOfClass:[Person class]]); 17 18 NSLog(@"========== 以上代码等价如下 ========="); 19 20 NSLog(@"%d", [NSObject isKindOfClass:[NSObject class]]); 21 NSLog(@"%d", [NSObject isMemberOfClass:[NSObject class]]); 22 NSLog(@"%d", [Person isKindOfClass:[Person class]]); 23 NSLog(@"%d", [Person isMemberOfClass:[Person class]]); 24 25 } 26 return 0; 27 }
日志信息
2 - isMemberOfClass 和 isKindOfClass 源代码
1 - (BOOL)isMemberOfClass:(Class)cls { 2 return [self class] == cls; 3 } 4 - (BOOL)isKindOfClass:(Class)cls { 5 for (Class tcls = [self class]; tcls; tcls = tcls->superclass) { 6 if (tcls == cls) return YES; 7 } 8 return NO; 9 } 10 11 12 + (BOOL)isMemberOfClass:(Class)cls { 13 return object_getClass((id)self) == cls; 14 } 15 16 17 + (BOOL)isKindOfClass:(Class)cls { 18 for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) { 19 if (tcls == cls) return YES; 20 } 21 return NO; 22 }
结论:isMemberOfClass 左边对象(类对象)是否等于右边所传进的类对象,是相等的关系
isKindOfClass 左边对象(类对象)是否等于右边所传进的类对象或是其子对象,是相等或是其子对象的关系
3 - 代码实例
1 #import <Foundation/Foundation.h> 2 #import <objc/runtime.h> 3 @interface Person : NSObject 4 5 @end 6 @implementation Person 7 8 @end 9 10 int main(int argc, const char * argv[]) { 11 @autoreleasepool { 12 13 // ----------------------------类方法 14 NSLog(@"%d", [Person isMemberOfClass:object_getClass([Person class])]); // 1 15 16 // NSObject 17 NSLog(@"%d", [Person isKindOfClass:object_getClass([NSObject class])]); // 1 18 NSLog(@"%d", [Person isKindOfClass:[NSObject class]]);// 1 19 20 // ----------------------------实例方法 21 id person = [[Person alloc] init]; 22 23 NSLog(@"%d", [person isMemberOfClass:[Person class]]); // 1 24 NSLog(@"%d", [person isMemberOfClass:[NSObject class]]); // 0 25 NSLog(@"%d", [person isKindOfClass:[Person class]]); // 1 26 NSLog(@"%d", [person isKindOfClass:[NSObject class]]); // 1 27 28 } 29 return 0; 30 }