私は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!
最初の検索を回避する方法はありません。しかし、配列に新しいものを追加し、並べ替えを維持し、配置された場所を覚えておくより効率的なやり方がありますか?
彼は新しいオブジェクトを追加するときに常に配列をソートする必要があると懸念しています。 –
@charith:私の指摘は、既存のコードのパフォーマンスが実際に問題になる可能性は低いということです。私はこれが実際にどれくらいの時間がかかるのか実際に見なくても、コンピュータが何をしているのか心配しているケースだと思います。 –
[CFBinaryHeap](http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFBinaryHeapRef/Reference/reference.html)は、自分自身のBツリーをローリングするのに適しているかもしれません。 –