2013-01-04 72 views
3

如何在coredata和xcode中插入多个/连续的新行?添加多个/连续的行 - 在Coredata中填充数据库

-(void)LoadDB{ 
    CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate]; 
    context = [appdelegate managedObjectContext]; 

    NSManagedObject *newPref;   
    newPref = [NSEntityDescription 
      insertNewObjectForEntityForName:NSStringFromClass([Preference class]) 
      inManagedObjectContext:context]; 
    NSError *error; 

    [newPref setValue: @"0" forKey:@"pid"];  
    [context save:&error]; 

    [newPref setValue: @"1" forKey:@"pid"];  
    [context save:&error]; 
} 

刚刚结束的代码写入了前一个条目。插入下一行的正确步骤是什么?

+1

Doc是你的朋友。 https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdCreateMOs.html –

+2

根据我的经验,苹果文档更多的是你在家庭聚会时被迫与之互动的表弟,对任何人都不是真正的朋友。 –

+0

准确@MechIntel – llBuckshotll

回答

6

您需要为每个核心数据管理对象提供一个新的插入语句。否则,你只能编辑现有的MO。而且,你只需要在最后保存一次。

-(void)LoadDB{ 
    CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate]; 
    context = [appdelegate managedObjectContext]; 

    NSManagedObject *newPref; 
    NSError *error; 

    newPref = [NSEntityDescription 
       insertNewObjectForEntityForName:NSStringFromClass([Preference class]) 
       inManagedObjectContext:context]; 
    [newPref setValue: @"0" forKey:@"pid"];  


    newPref = [NSEntityDescription 
       insertNewObjectForEntityForName:NSStringFromClass([Preference class]) 
       inManagedObjectContext:context]; 
    [newPref setValue: @"1" forKey:@"pid"];  

    // only save once at the end. 
    [context save:&error]; 
} 
+0

+1提及你应该只在你的修改结束时保存。这将DRAMATICALLY增加执行时间。还有其他一些事情要记住,以帮助您远离与Core Data的未来挂断。不要将核心数据视为数据库。它真的不是。这是一个对象图。每个新条目都是一个新对象,您必须创建该对象并链接到您想要的任何对象(尽管并非图表中的每个节点/对象都需要链接)。 –

+0

啊,我的错。我假设: '[context save:&error];' 是提交。我是newb =) – llBuckshotll

+0

这是提交,但在调用它之前,您可以在事务中添加很多内容。你甚至可以像上面的例子一样重复使用newPref变量,只要调用一个新的insertNewObjectForEntityForName方法即可。 –