Xcode 字符串比较仅与第一次匹配
我有一个排序数组,包含一长串演讲中所有发言者的姓名。我已经粘贴了下面的代码,但我的具体问题完全出现在第二个“for”循环中。有多个演示者在MyClass.Speechs中有多个条目。因此,当我第一次在第二个“for”循环中点击“if”语句时,它的计算结果为true,我看到log语句添加了一个speech。。。。然而,第二次它应该计算为true,正如“if”正上方的log语句所验证的那样,我从未看到添加了一个speech。。。打印到日志的行。那么,为什么我在“item.speaker”和“obj”第一次相同之后不输入“if”Xcode 字符串比较仅与第一次匹配,xcode,nsstring,Xcode,Nsstring,我有一个排序数组,包含一长串演讲中所有发言者的姓名。我已经粘贴了下面的代码,但我的具体问题完全出现在第二个“for”循环中。有多个演示者在MyClass.Speechs中有多个条目。因此,当我第一次在第二个“for”循环中点击“if”语句时,它的计算结果为true,我看到log语句添加了一个speech。。。。然而,第二次它应该计算为true,正如“if”正上方的log语句所验证的那样,我从未看到添加了一个speech。。。打印到日志的行。那么,为什么我在“item.speaker”和“obj”
[speakers sortUsingSelector:@selector(compare:)];
for (id obj in speakers) {
//now create a unique list of speakers
if ([uniqP containsObject:obj]) {
NSLog(@"already have this object");
}
else {
[uniqP addObject:obj];
//now that we've found a new speaker, we need to go through the entire list of speeches and populate
//them in the correct order.
self.speechesByPresenter = [[NSMutableArray alloc] init];
for (int j=0; j<numEntries; j++) {
SpeechesItem *item = [MyClass.speeches objectAtIndex:j];
NSLog(@" %@--%@--%d (%@)", item.speaker, obj, j, item.title);
if(item.speaker == obj) {
[self.speechesByPresenter addObject:item];
NSLog(@"added a speech, %@ now has %d", item.speaker, [self.speechesByPresenter count]);
}
}
}
}
不要使用item.speaker==obj来比较指针,而应该使用[item.speaker isEqualToString:obj]来比较字符串的内容。@lnafziger谢谢!代码辅助让我忘记了最基本方法的名称。speaker对象是什么类?如果它是一个NSString,那么@dasblinkenlight具有正确的代码。如果是自定义类,则需要实现isEqual和哈希函数,并使用isEqual而不是==。