Search code examples
objective-ccore-datamagicalrecord-2.2

CoreData update not working using MagicalRecord


I am trying to update an existing CoreData entity using MagicalRecord (version 2.3); this is my code:

PreferenceData *updateData = [PreferenceData MR_createEntityInContext:defaultContext];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"aHourFormat == %@ || aHourFormat == %@", [NSNumber numberWithInt: 12], [NSNumber numberWithInt: 24]];
updateData = [PreferenceData MR_findFirstWithPredicate: predicate inContext: defaultContext];

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *staffNamesArray = [[userDefaults arrayForKey:@"staffNamesArray"] mutableCopy];
NSMutableDictionary *preferencesDict = [[userDefaults dictionaryForKey:@"preferencesDictionary"] mutableCopy];

NSMutableArray *addlSvcsArray = [self createAddlSvcsTextboxArray];
NSMutableArray *customServicesArray = [[userDefaults arrayForKey:@"customServicesArray"] mutableCopy];

updateData.aStaffPos1 = staffNamesArray[0];
updateData.aStaffPos2 = staffNamesArray[1];
updateData.aStaffPos3 = staffNamesArray[2];
updateData.aStaffPos4 = staffNamesArray[3];
updateData.aStaffPos5 = staffNamesArray[4];
updateData.aStaffPos6 = staffNamesArray[5];

updateData.aShopOpens = [preferencesDict objectForKey:@"shopOpens"];
updateData.aShopCloses = [preferencesDict objectForKey:@"shopCloses"];

updateData.aDeleteOldAppts = [NSNumber numberWithInteger:[oDeleteAfterXDays.text intValue]];
updateData.aHourFormat = [NSNumber numberWithInt:[preferencesDict objectForKey:@"timeFormat"]];
updateData.aServicesType = [NSNumber numberWithInt:[preferencesDict objectForKey:@"servicesType"]];
updateData.aShowApptServices = [NSNumber numberWithInteger: @0];
updateData.aColorScheme = [preferencesDict objectForKey:@"colorScheme"];
updateData.aUpdatedRecordFlag = [NSNumber numberWithInteger: @1];

updateData.aAddlSvcs1 = addlSvcsArray[0];
updateData.aAddlSvcs2 = addlSvcsArray[1];
updateData.aAddlSvcs3 = addlSvcsArray[2];
updateData.aAddlSvcs4 = addlSvcsArray[3];
updateData.aAddlSvcs5 = addlSvcsArray[4];
updateData.aAddlSvcs6 = addlSvcsArray[5];

[defaultContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
    if(success)
        NSLog(@"update successful");
    else
        NSLog(@"update failed");
}];

}

I get no errors; the data is in the variables, but when I look at the record using sqlitebrowser, nothing has changed.

What am I doing wrong?


Solution

  • You first create a new record in updateData then you overwrite this variable with a search result. Each time you run the update you will create a new record which will just have defaults or be empty.

    If your data is not updated as expected, the updateData you fetch is most probably nil because something is wrong with the predicate.