Talha Ch Talha Ch - 1 month ago 7
Objective-C Question

MR_saveToPersistentStoreAndWait not saving data from array

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

}

Answer

You are working only with one managed object self.dxToAddEdit. And it will contain the last code from array. If you want to save multiple objects you should do the following:

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