Search code examples
iosobjective-cxcodecore-datamagicalrecord

Magical Record - adding values to entity in loop


I have problem with my Magical Record code:

    Collection *collection = [Collection MR_createEntity];
    [collection setValue:name forKey:@"name"];
    [collection setValue:date forKey:@"date"];
    [collection setValue:amount forKey:@"amount"];

    for (Person *person in self.selectedPeople) {
        Payment *payment = [Payment MR_createEntity];
        [payment setValue:person forKey:@"person"];
        [payment setValue:collection forKey:@"collection"];
    }

   [[NSManagedObjectContext MR_defaultContext]  MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            NSLog(@"Item %@ added to database", collection.name);
    }];

For every person that user selected i want to create a payment in database. I'm doing that in the loop. My problem is only the last payment has collection.

For example when I have 3 people it looks like that:

Payment 1 - person:John, collection: nil
Payment 2 - person:Bill, collection: nil
Payment 3 - person:Mark, collection: Paper

Anyone can tell me why is that happening?


Solution

  • My guess is that it's the relationship from collection to payment. You are trying to use a many-to-one from collection to payment, but you might only have a one-to-one setup in your Core Data model.

    I'm not sure that a many-to-one relationship is a good idea from collection to payment. You might want to create a unique entity for each collection, but that all depends on your model.

    for (Person *person in self.selectedPeople) {
        // Create a new collection entity for each payment.
        Collection *collection = [Collection MR_createEntity];
        [collection setValue:name forKey:@"name"];
        [collection setValue:date forKey:@"date"];
        [collection setValue:amount forKey:@"amount"];
    
        Payment *payment = [Payment MR_createEntity];
        [payment setValue:person forKey:@"person"];
        [payment setValue:collection forKey:@"collection"];
    }
    
    [[NSManagedObjectContext MR_defaultContext]  MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            NSLog(@"Item %@ added to database", collection.name);
    }];