2013-10-21 74 views
0

我正在使用核心數據將數據存儲在我的i​​OS應用程序中。有兩個實體,從一個實體到另一個實體(例如1個課程 - >許多學生,1個學生 - >許多年級)具有一對多關聯,並且是相反的。CoreData不會保存參考對象

每當我創建一個學生(或成績)的新實例並通過課程(或學生)(NSManagedObject)時,該引用無法保存並且變爲null。沒有例外,對象的所有其他值都被保存,但對課程的引用是null

我在做什麼:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context]; 
Student *newStudent = (Student *)[[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:context]; 


[newStudent setLastname:_lastname.text]; 
[newStudent setFirstname:_firstname.text]; 
[newStudent setNote:_note.text]; 

NSNumber *tmp = [NSNumber numberWithInt:(int)[[(AppDelegate *)[[UIApplication sharedApplication]delegate] staticDataObject]increaseGlobalSchuelerID]]; 
[newStudent setId:tmp]; 


[newStudent setCourse:(Course *)_detailItem]; 
[newStudent setDesktopID:[NSNumber numberWithInt:-1]]; 


NSError *error = nil; 
if (![context save:&error]) { 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

的_detailItem是實體course的NSManagedObject。你們有什麼想法,爲什麼這不起作用?

在此先感謝!

+1

你確定'_detailItem'是一個有效的引用?你可以在保存之前記錄學生和課程('_detailItem')嗎? – Wain

回答

0

也許你可以嘗試在同一時間建立反向關係,這意味着將newstudent添加到_detailItem中。我以這種方式昨天解決了類似的問題,但真的不知道爲什麼。