MR_saveToPersistentStoreAndWait不保存数组中的数据

问题描述:

我有一个NSArray,我在用户从tableview中选择多行后添加对象。选择用户后按确认并保存数据。所以根据我在这里找到的一些例子,我已经实现了代码,但它似乎一次只保存一个值。该用户选择的最后一个值:MR_saveToPersistentStoreAndWait不保存数组中的数据

- (IBAction)confirmPressed:(id)sender { 
    NSLog(@"Selected Are: %@ - %@",selectedDX,selectedDesc); 
    for (NSString *code in selectedDX) { 
     if (!_dxToAddEdit) { 
      self.dxToAddEdit = [Diagnoses MR_createEntity]; 
     } 

     [self.dxToAddEdit setCode:code]; 
     [self.dxToAddEdit setCodeDescription:@"Sample Description"]; 
     [self.dxToAddEdit setSuperBill:_forSuperBill]; 

     [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait]; 
} 
    [self.navigationController popViewControllerAnimated:YES]; 

} 

您只使用了一个管理对象self.dxToAddEdit。它将包含数组中的最后一个code。如果要保存多个对象,则应该执行以下操作:

NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext]; 
for (NSString *code in selectedDX) { 
    Diagnoses *newDiagnose = [Diagnoses MR_createEntityInContext:defaultContext]; 

    newDiagnose.code = code; 
    newDiagnose.codeDescription = @"Sample Description"; 
    newDiagnose.superBill = _forSuperBill; 
} 

// Save recently created objects to persistent store. 
[defaultContext MR_saveToPersistentStoreAndWait];