我有一個排序數組,包含一系列演示文稿中所有揚聲器的名稱。我粘貼了下面的代碼,但是我的具體問題完全在第二個for循環中。有多個演示者在MyClass.speeches中擁有多個條目。因此,我第一次在'for'循環中敲入'if'語句,並且它的計算結果爲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]);
}
}
}
}
揚聲器對象是什麼類?如果它是一個NSString,那麼@dasblinkenlight具有正確的代碼。如果它是一個自定義類,那麼你需要實現'isEqual'和'hash'函數,並使用'isEqual'而不是== ==。 – lnafziger 2012-08-06 03:48:17