I'm using Core Data + sqlite as a data cache. The app reads in a file into core data, then uses Core Data to run the app. Saves are done to both the NSManagedObjectContext and to the file. I've noticed, though, if I quit the app and reload it without repopulating the Core Data database, some (but not all) of the data saved using -save: is not being saved to the data store.
Changes to my managed object are all done in a single batch on the main thread, with the -save: message being sent after all changes are comple开发者_运维百科ted. The data that isn't being saved is a transformable attribute, the only transformable attribute in the core data object. Here's the code that saves the object:
NSInteger columnIndex = [headers indexOfObject:questionID];
if (NSNotFound != columnIndex) {
// parsedLine is a mutable array already
NSMutableArray *parsedLine = person.dataFromFile.parsedLine;
[parsedLine replaceObjectAtIndex:columnIndex withObject:answer];
person.dataFromFile.parsedLine = parsedLine;
person.questionsAnsweredByPerson = [NSNumber numberWithInt:[FileParser questionsAnsweredInRow:person.dataFromFile.parsedLine withRowHeaders:headers]];
person.address.street.questionsAnsweredByPeopleOnStreet = [NSNumber numberWithInt:[self questionsAnsweredByPeopleOnStreet]];
//NSLog(@"rawLineBefore:\n%@", person.dataFromFile.rawLine);
person.dataFromFile.rawLine = [ReconstructCSV composeCSVLineFromArray:person.dataFromFile.parsedLine];
//NSLog(@"rawLineAfter:\n%@", person.dataFromFile.rawLine);
Voter_SurveyAppDelegate *appDelegate = (Voter_SurveyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSError *error;
NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
if (![managedObjectContext save:&error]) {
// XXX inform the user there was a fatal error opening the file. Low disk space?
NSLog(@"Unresolved error - could not save managedObjectContext - %@, %@", error, [error userInfo]);
abort();
}
return YES;
}
abort(); is not getting called, so I assume -save; is getting called properly.
I doubt it is related, but after this code is run on the main thread, I perform an NSFetchRequest using a new NSManagedObjectContext on a different thread. Nothing else takes place related to Core Data on other threads.
Why isn't the transformable attribute getting saved?
The problem is that transformable properties don't like Mutable objects. As noted in an answer to this question, an NSMutableDictionary wasn't getting saved. In my case, it was an NSMutableArray.
精彩评论