2013-01-04 76 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方法即可。 –