Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App freeze on CoreData save

I have an iPhone app that freezes sometimes when saving CoreData and then doesn't relaunch. I did have a second thread that uses the database, but I think I have followed the pattern to make a separate context for that thread. Here is the crash report from the relaunch. Any ideas?

I have tried changing it to only run with one thread and here is the latest freeze point after entering the background.

#0  0x30851b98 in fsync
#1  0x3094e694 in _sqlite3_purgeEligiblePagerCacheMemory
#2  0x3094e6b8 in _sqlite3_purgeEligiblePagerCacheMemory
#3  0x30945372 in sqlite3_compileoption_get
#4  0x30957f06 in sqlite3_extended_errcode
#5  0x3095dc20 in sqlite3_extended_errcode
#6  0x3095dd8e in sqlite3_extended_errcode
#7  0x309646f8 in sqlite3_clear_bindings
#8  0x3098845a in sqlite3_open16
#9  0x3094495a in sqlite3_step
#10 0x31a1dc20 in _execute
#11 0x31acc6e8 in -[NSSQLiteConnection commitTransaction]
#12 0x31aca646 in -[NSSQLiteConnection endPrimaryKeyGeneration]
#13 0x31abeab4 in -[NSSQLCore prepareForSave:]
#14 0x31a4acd0 in -[NSSQLCore saveChanges:]
#15 0x31a1591e in -[NSSQLCore executeRequest:withContext:error:]
#16 0x31a1538a in -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
#17 0x31a48544 in -[NSManagedObjectContext save:]
#18 0x000080aa in -[KPersistence saveManagedObjects:] at KPersistence.m:242
#19 0x00004320 in -[KinKastAppDelegate applicationDidEnterBackground:] at KinKastAppDelegate.m:126

Here is my implementation of saveManagedObjects

-(BOOL)saveManagedObjects:(NSError **)error
{
    [persistentStoreCoordinator lock];
    BOOL success = YES;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:error]) {
            VLog(@"Unresolved error %@, %@", *error, [*error userInfo]);
            success = NO;
        } 
    }
    [persistentStoreCoordinator unlock];
    return success;
}
like image 468
Tom Belote Avatar asked Mar 08 '11 18:03

Tom Belote


1 Answers

When using Core Data from multiple threads, make sure to lock your PSC before a save operation:

[self.persistentStoreCoordinator lock];
NSManagedObjectContext *context = //your context;
[context save:&error];
if (error) {
    // handle error
}
[self.persistentStoreCoordinator unlock];
like image 56
amattn Avatar answered Oct 15 '22 15:10

amattn