2012-02-09 76 views
1

我試圖讓我的頭圍繞核心數據,我想實現一個小一對多的關係,但我不斷收到以下錯誤:錯誤保存了許多關係到核心數據

我有兩個NSManagedObject由Xcode的數據模型創建的類(組和聯繫人)具有多對多關係。

@implementation Groups 
@dynamic groupId; 
@dynamic groupName; 
@dynamic groupContacts; 
@end 

@implementation Contacts 
@dynamic firstName; 
@dynamic lastName; 
@dynamic userId; 
@dynamic belongsToGroup; 

我有接觸數據字典的數組,我做了以下內容:

self.localGroup = [NSEntityDescription insertNewObjectForEntityForName:@"Groups" inManagedObjectContext:self.scratchPadContext]; 
self.localGroup.groupName = @"Some Name"; 

    for (int i = 0; i < [self.ContactsData count]; i++) { 
     Contacts *contact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:self.scratchPadContext];   
     NSDictionary *obj = (NSDictionary *)[self.ContactsData objectAtIndex:i]; 

     contact.firstName = [obj valueForKey:@"firstName"]; 
     contact.userId = [obj valueForKey:@"email"]; 

     [self.localGroup addGroupContactsObject:contact]; 
    } 

    if (![self.scratchPadContext save:&error]) { 
     NSLog(@"Errror saving Group ********************************* %@, %@", error, [error userInfo]); 
    } 

我收到以下錯誤:

[4459:15503] Errror saving Group ***************** Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn’t be completed. (Cocoa error 134030.)" UserInfo=0x85e0ab0 {NSAffectedObjectsErrorKey=( " (entity: Groups; id: 0x838d020 ; data: {\n groupContacts = nil;\n groupId = 0;\n groupName = Some Name;\n})"), NSUnderlyingException=Cannot update object that was never inserted.}, { NSAffectedObjectsErrorKey = ( " (entity: Groups; id: 0x838d020 ; data: {\n groupContacts = nil;\n groupId = 0;\n groupName = Some Name;\n})" ); NSUnderlyingException = "Cannot update object that was never inserted."; }

如果我註釋掉的關係部件並保存組名稱,它工作正常。所以,我想問題是關係數據,但我無法弄清楚什麼。任何人都可以請指我到哪裏我可以做錯了嗎?

[編輯]:

當我添加

contact.belongsToGroup = self.localGroup; 

即使我使用一個MOC我碰到下面的錯誤。我無法理解錯誤在哪裏。如果有人能夠闡明這一點,我將不勝感激。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'belongsToGroup' between objects in different contexts (source = <Contacts: 0x86926a0> (entity: Contacts; id: 0x8692700 <x-coredata:///Contacts/t2548922E-A0C6-4E3C-9760-3265954764E73> ; 
+0

任何接受者??我一直堅持這一兩天了......任何關於如何進行的指針都會非常讚賞泰德! – iKT 2012-02-11 00:17:50

+0

我需要看看你是如何創建你的託管對象上下文等 – fisk 2012-03-04 11:04:12

回答

1

你試過保存scratchPadContext添加聯繫人到組(即創建localGroup對象,保存上下文,然後添加聯繫人,並再次保存上下文?從錯誤信息,看起來Core Data在發送必要的插入內容之前會向永久存儲區發送更新語句,所以它可能會因爲您將永久存儲區的新對多關係的兩端寫入相同而被絆倒時間。