Talha Ch Talha Ch - 1 month ago 5
iOS Question

How to save data in two NSMutableArray into a single entity using magical record

I'm fetching

code
&
desc
from web by calling an API. Then loading it into
tableView
and based on multiple selection I'm saving the selected values into two arrays i.e.
selectedCode
and
selectedCodeDesc
. My Entity is:


enter image description here


So I want to
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error){
but don't know how. I know this much:

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

[self.dxToAddEdit setCode:code];
[self.dxToAddEdit setCodeDescription:@""]; //what to give here
[self.dxToAddEdit setSuperBill:_forSuperBill];
}
//after this I'm calling the saveToPersistent


So what to give at setCodeDescription?

Answer

If I understood correctly and based on your description and example of code you can do the following:

NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];
// Sorry, I renamed selectedCode to selectedCodes and selectedCodeDesc to selectedCodeDescriptions for readability.
// Not sure whether selectedDX is actually selectedCodes.
for (NSInteger i=0; i<selectedCodes.count; ++i) {
    NSString *code = selectedCodes[i];
    NSString *description = selectedCodeDescriptions[i];
    Diagnoses *newDiagnose = [Diagnoses MR_createEntityInContext:defaultContext];

    newDiagnose.code = code;
    newDiagnose.codeDescription = description;
    newDiagnose.superBill = _forSuperBill;
}

[defaultContext MR_saveToPersistentStoreAndWait];

Actually, I would not save the response into two separated arrays. Because of:

  • Your code becomes difficult to read
  • Imagine that the model will change and instead of two properties it will contain 4. You will have to create additional arrays.

I would recommend you to parse the response directly into the managed objects. Of course, you may not save them into persistent storage just populate your table view. I highly recommend you to read these tutorials about Core Data. It will give you insight how to work with Magical Record library. Although, the library simplifies a lot of work it would be better to know what is under the hood ;]