我有一個名爲Topic的類的已排序可變數組。主題代表一系列出版物。我將這些主題呈現在表格中,並定期從Web服務中獲取新的出版物。當新的出版物到達時,我想用動畫添加到表格中。添加對象到已排序的NSMutable數組並回答索引路徑
讓我煩惱的是我需要做的計算工作來添加到這個數組中,並回答正確的索引路徑。有人可以建議一個比這更直接的方式:
// add a publication to the topic model. if the publication has a new topic, answer
// the index path of the new topic
- (NSIndexPath *)addPublication:(Publication *)pub {
// first a search to fit into an existing topic
NSNumber *topicId = [pub valueForKey:@"topic_id"];
for (Topic *topic in self.topics) {
if ([topicId isEqualToNumber:[topic valueForKey:"id"]]) {
// this publication is part of an existing topic, no new index path
[topic addPublication:pub];
return nil;
}
}
// the publication must have a new topic, add a new topic (and therefore a new row)
Topic *topic = [[Topic alloc] initWithPublication:publication];
[self.topics addObject:topic];
// sort it into position
[self.topics sortUsingSelector:@selector(compareToTopic:)];
// oh no, we want to return an index path, but where did it sort to?
// yikes, another search!
NSInteger row = [self.topics indexOfObject:topic];
return [NSIndexPath indexPathForRow:row inSection:0];
}
// call this in a loop for all the publications I fetch from the server,
// collect the index paths for table animations
// so much computation, poor user's phone is going to melt!
有沒有得到周圍的第一次搜索,我猜。但是有沒有更有效的方法來將新事物添加到數組中,保持排序並記住它放置的位置?
他擔心的是他需要在添加新對象時總是對數組進行排序。 – 2012-03-26 05:33:28
@ charith:我的觀點是,現有代碼的性能不太可能成爲問題。我相信這是一個擔心計算機在做多少工作而沒有真正看到需要多少時間的情況。 – 2012-03-26 05:37:44
[CFBinaryHeap](http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFBinaryHeapRef/Reference/reference.html)可能是滾動自己的B樹的好選擇。 – 2012-03-26 05:38:22