iPhone Core Data 一次保存多个项目的随机行为?
我有一个应用程序,它读取 rss feed、解析 xml 并使用 Core Data 将其添加到我的数据库中(这样即使没有可用的互联网连接,用户也可以看到 feed),这一切都工作正常。我进行解析的方式是:在 didStartElement 上创建一个新实体,例如:
NewsDB *newsDB = [NSEntityDescription insertNewObjectForEntityForName:@"NewsDB" inManagedObjectContext:managedObjectContext];
self.currentObject = newsDB;
在 didendDocument 中,我只是用以下内容保存所有内容:
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSError *error = nil;
if (![managedObjectContext save:&error])
{
NSLog(@"Error saving %@", error);
}
这个 al 工作得很好,事实上,我的程序按照我想要的方式工作现在。但我的问题是,当保存托管对象上下文时,项目似乎是随机添加的,这是上下文中第一个创建的对象可能不是数据库中的第一行。我通过添加一列来解决此问题,该列告诉我在 xml 中的位置,然后在 fetchedResultsController 中简单地按此列进行排序。
我知道我可以在每次项目结束时保存上下文,但这听起来不是一个好方法,所以我只是在最后保存它们。
我的问题是为什么它们会随机添加?这是正常行为吗?谢谢。
-奥斯卡
I have an application that reads an rss feed, parses the xml and adds it to my database using Core Data (this is so the user can see the feed even if no internet connection is available) this all works fine. The way I am doing the parsing is: on the didStartElement i create a new Entity such as:
NewsDB *newsDB = [NSEntityDescription insertNewObjectForEntityForName:@"NewsDB" inManagedObjectContext:managedObjectContext];
self.currentObject = newsDB;
and in the didendDocument i just save everything with something such as:
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSError *error = nil;
if (![managedObjectContext save:&error])
{
NSLog(@"Error saving %@", error);
}
This al works perfectly fine, in fact my program works just the way I want it now. But my question is when the managed object context gets saved the items seem to be added randomly, this is the first created object in the context may not be the first row in the database. I fixed this by adding a column that tells me the position in the xml, and then simply sorting by this column in my fetchedResultsController.
I know I could just save the context every time an item ends, but that doesn't sound like a good approach, so I just save them all at the end.
My question is why do they get added randomly?, is this the normal behavior?. Thank you.
-Oscar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Core Data 的货币是
NSSet*
实例。集合是无序的,因此您添加然后取回的任何内容都将返回给您,而没有任何内在顺序。因此,您只需在初始化
NSFetchedResultsController
时应用NSSortDescriptor
即可。您可以根据需要应用任意数量的排序顺序,例如:The currency of Core Data are
NSSet*
instances. Sets are unordered, so anything you add and then fetch back will come back to you without any intrinsic ordering.So you just need to apply an
NSSortDescriptor
when you initialize yourNSFetchedResultsController
. You can apply as many sort orderings as you like, e.g.:这是正常行为。您可能还注意到,当您创建一对多关系时,相关属性是一个无序集合(NSSet)。
当顺序很重要时,只需像您所做的那样添加用于排序的数字属性。
This is normal behavior. You may have also noticed that when you create a to-many relationship that the related property is an unordered collection (NSSet).
When order matters, simply add a number attribute for sorting as you have done.