我正在将字典(单词列表,而不是类别)作为 NSString 加载到 NSSet 中。然后我重复发送此设置消息 -containsObject:someNSString。但它总是返回错误。我写了一些代码来测试它:
NSLog(@"Random from dictionary: %@", [dictionary anyObject]);
NSString *test = [NSString stringWithFormat:@"BEMIRED"];
NSLog(@"To match this word: %@", test);
if ([dictionary containsObject:test])
NSLog(@"YES!");
在日志中我得到以下内容:
Random from dictionary: BEMIRED
To match this word: BEMIRED
(我错过了“是!”)
当我尝试使用 CFShow(dictionary) 时,我可以看到它实际上包含字符串和所有内容。一个例子:
0 : <CFString 0xc3bd810 [0x1386400]>{contents = "BEMIRED"}
3 : <CFString 0xdf96ef0 [0x1386400]>{contents = "SUBJECTIFIED"}
有人可以帮我吗? 谢谢!
最佳答案
NSSet 使用 isEqual:
来测试对象是否相等,NSString 会覆盖它以执行您期望的字符串比较。以下单元测试通过:
- (void)testSetStrings
{
NSSet *set = [NSSet setWithObject:@"String 1"];
// I've used the UTF8 initializer to avoid any cleverness from reusing objects
NSString *string1 = [[[NSString alloc] initWithUTF8String:"String 1"] autorelease];
// Test the references/pointers are not the same
STAssertTrue([set anyObject] != string1, nil);
STAssertTrue([set containsObject:string1], nil);
}
我们可以看到这两个字符串具有不同的指针值,但该集合仍然为 containsObject:
调用返回 YES。
所以我猜你的字符串实际上并不相等。我会检查隐藏的空格或其他类似问题。
关于objective-c - 带有 NSStrings containstObject 的 NSSet 在应该时不返回 YES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037474/