标签:NSLog OC isMemberOfClass Person isKindOfClass NSObject class
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 }
标签:NSLog,OC,isMemberOfClass,Person,isKindOfClass,NSObject,class
来源: https://www.cnblogs.com/self-epoch/p/16538816.html
本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。