Question

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!!
Was it helpful?

Solution

managed context is not thread safe, but you can have as many managed contexts as you like, that might have something to do with this. Perhaps remove the dispatch async, you don't need it as you are doing the code on main thread.

I make a background managed context in a data manager class, where I do all my writes and when I need to, I listen do a notification name MANAGEDCONTEXTDIDSAVE and reload if I need to.

Works like a charm.

OTHER TIPS

the problem is sort of fixed, I had to turn off and reset my phone to get it to work...

but still don't know why this could happen

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top