【发布时间】:2012-03-26 05:00:06
【问题描述】:
我有一个名为 Topic 的类的排序可变数组。主题代表一组出版物。我在表格中显示主题,并定期从 Web 服务获取新出版物。当新的出版物到来时,我想用动画添加到表格中。
困扰我的是我需要做的计算工作才能添加到这个数组中,并回答正确的索引路径。有人可以提出比这更直接的方法吗:
// 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!
我猜,第一次搜索是无法绕过的。但是有没有更有效的方法来向数组中添加新事物、维护排序并记住它的放置位置?
【问题讨论】:
标签: iphone objective-c nsmutablearray nsindexpath