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),它给出:
2013-05-07 12:35:45.249 Test[27483:303] c1: ‘_NSCFConstantString’,c2: ‘_NSCFConstantString’
2013-05-07 12:40:06.673 Test[27542:303] *c1: ‘0x7fff7d2bd740’,*c2: ‘0x7fff7d28ae48’
2013-05-07 12:35:45.250 Test[27483:303] == not equal
2013-05-07 12:35:45.251 Test[27483:303] isEqual: not equal
2013-05-07 12:35:45.251 Test[27483:303] name equal
在iOS(6.1)这里给出:
2013-05-07 12:38:11.816 Test[27516:11303] c1: ‘_NSCFConstantString’,c2: ‘_NSCFConstantString’
2013-05-07 12:41:01.319 Test[27557:11303] *c1: ‘0x1db88f8’,*c2: ‘0x1db88f8’
2013-05-07 12:38:11.816 Test[27516:11303] == equal
2013-05-07 12:38:11.816 Test[27516:11303] isEqual: equal
2013-05-07 12:38:11.816 Test[27516:11303] name equal
关键的区别似乎是在iOS下,两个Class值是相同的对象,但在OS X下,它们是两个不同的对象.
因此,至少在OS X下使用==或isEqual:比较两个类值是不安全的.我找不到任何函数来比较两个Class值,所以使用class_getName似乎是最好的选择.