objective-c – 为什么是OS X上的[@“”class]!= NSClassFromSt
if([@"" class] == NSClassFromString(NSStringFromClass([@"" class]))) printf("foo"); else printf("bar"); 输出iOS:foo OS X上的输出:bar 为什么OS X上的这个行为奇怪? 解决方法
有趣的问题以下指出了评论中提到的一些事情:
Class c1 = [@"" class]; Class c2 = NSClassFromString(NSStringFromClass([@"" class])); // The names are the same under iOS and OS X NSLog(@"c1: '%@',c2: '%@'",c1,c2); // The pointers are the same under iOS but different under OS X NSLog(@"*c1: '%p',*c2: '%p'",c2); if (c1 == c2) { NSLog(@"== equal"); // iOS } else { NSLog(@"== not equal"); // OS X } if ([c1 isEqual:c2]) { NSLog(@"isEqual: equal"); // iOS } else { NSLog(@"isEqual: not equal"); // OS X } const char *n1 = class_getName(c1); const char *n2 = class_getName(c2); if (strcmp(n1,n2) == 0) { NSLog(@"name equal"); // Both iOS and OS X } else { NSLog(@"name not equal"); } 在Mac上(OS X 10.7.5),它给出:
在iOS(6.1)这里给出:
关键的区别似乎是在iOS下,两个Class值是相同的对象,但在OS X下,它们是两个不同的对象. 因此,至少在OS X下使用==或isEqual:比较两个类值是不安全的.我找不到任何函数来比较两个Class值,所以使用class_getName似乎是最好的选择. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |