一千萬個為什麽

搜索

應用凍結CoreData保存

我有一個iPhone應用程序,有時在保存CoreData時凍結,然後不重新啟動。我確實有一個使用數據庫的第二個線程,但我認為我已經遵循該模式為該線程創建一個單獨的上下文。以下是重新啟動的崩潰報告。有任何想法嗎?

我嘗試將其更改為僅使用一個線程運行,這是進入後臺後的最新凍結點。

#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

這是我的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;
}

最佳答案

從多個線程使用Core Data時,請確保在保存操作之前鎖定PSC:

[self.persistentStoreCoordinator lock];
NSManagedObjectContext *context = //your context;
[context save:&error];
if (error) {
   //handle error
}
[self.persistentStoreCoordinator unlock];

轉載註明原文: 應用凍結CoreData保存