我有一个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;
}
答案 0 :(得分:13)
从多个线程使用Core Data时,请确保在保存操作之前锁定PSC:
[self.persistentStoreCoordinator lock];
NSManagedObjectContext *context = //your context;
[context save:&error];
if (error) {
// handle error
}
[self.persistentStoreCoordinator unlock];
答案 1 :(得分:2)
所以我现在相信问题是我有时会将带浮点值的NSNumber写入整数字段。这导致内存中的副本与从数据库中读取的副本不同,这导致无限合并循环。但是,如果你重新启动应用程序它工作正常,因为从那时起该值只是一个整数。