MR_saveToPersistentStoreAndWait 不保存数组中的数据

MR_saveToPersistentStoreAndWait not saving data from array

我有一个 NSArray,我在用户从表视图中选择多行后添加对象。选择用户后按确认并保存数据。因此,根据我在这里找到的一些示例,我已经实现了代码,但它似乎一次只保存一个值。用户选择的最后一个值:

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