I am developing an app that communicates with a server, and saves to core data.
in appDelegate, I started my singleton object and called useDocument to initialize UIManagedDocument:
- (void)useDocument
{
if (![[NSFileManager defaultManager] fileExistsAtPath:self.database.fileURL.path]){
[self.database saveToURL:self.database.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:nil];
} else if (self.database.documentState == UIDocumentStateClosed){
[self.database openWithCompletionHandler:nil];
}
}
heres the code upon receiving data from server:
- (void)downloadCompletedWithData: (NSData *)data item: (TPDownloadItem *)finishedItem;
{
// parse data and update core
NSError *error;
id dataObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (dataObject && !error){
dispatch_async(dispatch_get_main_queue(), ^{
[User createUserWithInfo:dataObject inManagedContext:self.database.managedObjectContext];
});
}
}
heres the code that writes to core data:
+ (id)createUserWithInfo: (NSDictionary *)userInfo inManagedContext: (NSManagedObjectContext *)aContext
{
NSError *error;
User *aUser = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:aContext];
NSString *userID = [userInfo objectForKey:USER_ID];
aUser.userID = userID;
aUser.effective = [NSNumber numberWithBool:[[userInfo objectForKey:USER_EFFECTIVE] boolValue]];
aUser.job = [userInfo objectForKey:USER_JOB];
aUser.gender = [userInfo objectForKey:USER_GENDER];
return aUser;
}
The problem is that whenever core data tries to auto save (waited for about 30 sec) the app crashes with the following error:
I tried to call "useDocument" and "createUser" in the main thread using GCD, also override UIDocument "contentsForType" to make sure it happens right after autosave, document state is normal before it saves, and persistence store file is also created.
- Does anyone encounter similar situation? any help is very much appreciated!!