我正在嘗試學習Core Data,並且在將新對象添加到現有對象後更新MOC時遇到問題。我可以創建原始對象,一個訓練日,並且我可以將訓練對象添加到該訓練日,但我無法弄清楚如何保存上下文,以便稍後在我的應用程序中可以在訓練日中找到所有練習。保存特定對象的managedObjectContext
任何想法??
這裏是我的代碼:
// Data from JSON
NSArray *trainingDayData = responseData[@"training_days"];
for (NSDictionary *aTrainingDay in trainingDayData) {
// Find the specific training day and save the MOC, creating the trainingDayObject
NSNumber *idTrainingDay = [NSNumber numberWithInt:[[aTrainingDay objectForKey:kID_KEY] intValue]];
VitTrainingDay *trainingDayObject = [VitTrainingDay trainingDayCreateOrObjectWithID:idTrainingDay];
// Configure the VitTrainingDay object's fields
trainingDayObject.name = aTrainingDay[@"name"];
trainingDayObject.order = aTrainingDay[@"order"];
}
// assign exercises to each trainingDayObject(this is inside a larger for loop)
trainingDayObject.userExercise = [NSSet setWithArray:userExerciseObjects];
// Below are attempt one and two to update the MOC after assigning exercises to the trainingDayObject.
// This works to save the updated MOC, but also adds two blank trainingDayObjects, since it 'insertNewObjectForEntityName', which I don't want.
trainingDayObject = [NSEntityDescription insertNewObjectForEntityForName:@"TrainingDay" inManagedObjectContext:self.context];
//This as far as I can tell is doing nothing. It just points to the conventional MOC save method. I pull it out below.
[self.coreDataManager saveContextForManagedObjectContext:self.context];
這裏是saveContextForManagedObjectContext
方法我稱之爲上面:
- (void)saveContextForManagedObjectContext:(NSManagedObjectContext *)moc
{
NSError *error = nil;
if (![moc save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
我仍然遇到同樣的問題。它按預期工作,如果我設置了一個斷點,我可以看到練習被分配到訓練日,並且調用了「NSLog(@」保存成功「);',但練習沒有被保存到出於某種原因的培訓日期。我已經成功地通過使用'trainingDayObject = [NSEntityDescription entityForName:@「trainingDay」inManagedObjectContext:self.context]獲得了保存到訓練日的練習;'但是這給了我警告:'不兼容的指針類型分配給'VitTrainingDay * '來自'NSEntityDescription *'' – Arel
發佈VitTrainingDay –
的定義'VitTrainingDay'是'TrainingDay'核心數據的一個'NSManagedObject'子類實體 – Arel