字符串比较仅匹配第一次

时间:2012-08-06 03:35:36

标签: xcode nsstring

我有一个排序数组,其中包含一系列演示文稿中所有发言人的姓名。我已粘贴下面的代码,但我的具体问题完全在第二个'for'循环中。有多个演示者在MyClass.speeches中有多个条目。所以我第一次在第二个'for'循环中点击'if'语句,并且计算结果为true,我看到日志语句“添加了一个语音......”。但是,第二次它应该评估为true(由'if'上方的日志语句验证),我从未在日志中看到“添加语音...”行。那么为什么我第一次'item.speaker'和'obj'相同后才输入'if'?

[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]);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

而不是比较指针的item.speaker == obj,而应使用[item.speaker isEqualToString:obj]来比较字符串的内容。