我有以下代码
NSMutableArray *mutArray = [[NSMutableArray alloc] init];
[mutArray addObject: [NSProcessInfo processInfo]];
[mutArray addObject: @"This is NSString Object"];
[mutArray addObject: [[NSMutableString alloc] initWithString: @"1st Mutable String"]];
for (id element in mutArray){
NSLog(@" ");
NSLog(@"Class Name: %@", [element className]);
NSLog(@"Is Member of NSString: %@", ([element class] isMemberOfClass: [NSString class]) ? YES: NO);
NSLog(@"Is kind of NSString: %@", ([element class] isKindOfClass: [NSString class]) ? YES: NO);
}
我得到了以下输出(并且期望指出)
Class Name: NSProcessInfo
Is Member of NSString: NO
Is Kind of NSString: NO
Class Name: NSCFString <-- Expecting NSString
Is Member of NSString: NO <-- Expecting YES
Is Kind of NSString: NO <-- Expecting YES
Class Name: NSCFString <-- Expecting NSMutableString
Is Member of NSString: NO
Is Kind of NSString: NO <-- Expecting YES
我在这里错过了一些可怕的简单吗?谢谢!
答案 0 :(得分:16)
使用:
[element isMemberOfClass: [NSString class]]
不
[[element class] isMemberOfClass: [NSString class]]
NSString和NSMutableString实现为class cluster(参见iPhone version of the documentation中的“字符串对象”)。
所以isKindOfClass:应该返回true但isMemberOfClass:将返回false,因为NSString不是对象的确切类型。
答案 1 :(得分:2)
NSString
由一组类组成。它们也与CFString
s(来自CoreFoundation
)进行免费桥接。这很可能出现在NSString
这个NSCFString
的实现中(我不知道所有的事实,但我在这里的推论是这个类充当了桥梁。)