MR_saveToPersistentStoreAndWait not saving data from array

时间:2016-10-14 14:03:09

标签: ios objective-c core-data magicalrecord

I've an NSArray in which I'm adding objects after user selects multiple rows from a tableview. After selecting user press confirm and it saves the data. So based on some example I found here I have implemented the code but it seems as it is only saving one value at a time. The last value that user selects:

- (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];

}

1 个答案:

答案 0 :(得分:1)

您只使用一个托管对象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];