Ich habe ein sortiertes veränderbares Array einer Klasse namens Topic. Die Themen repräsentieren eine Reihe von Publikationen. Ich präsentiere die Themen in einer Tabelle und hole regelmäßig neue Publikationen von einem Web-Service ab. Wenn eine neue Publikation eintrifft, möchte ich sie mit einer Animation zur Tabelle hinzufügen.Objekt zu sortierten NSMutable-Array hinzufügen und Indexpfad antworten
Was mich stört, ist die Rechenarbeit, die ich tun muss, um in dieses Array hinzuzufügen und den richtigen Indexpfad zu beantworten. Kann jemand einen direkteren Weg als das vorschlagen:
// 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!
Es gibt keine um die erste Suche, ich denke. Aber gibt es eine effizientere Möglichkeit, einem Array eine neue Sache hinzuzufügen, eine Art zu pflegen und sich daran zu erinnern, wo es platziert wurde?
Seine Sorge ist er muss das Array immer sortieren, wenn er ein neues Objekt hinzufügt. –
@charith: Mein Punkt ist, dass die Leistung des vorhandenen Codes wahrscheinlich kein Problem ist.Ich glaube, das ist ein Fall von Sorgen darüber, wie viel Arbeit der Computer macht, ohne tatsächlich zu sehen, wie viel Zeit er benötigt. –
[CFBinaryHeap] (http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFBinaryHeapRef/Reference/reference.html) ist möglicherweise eine gute Alternative zum Rollen des eigenen B-Baums. –