首页 > ios 在多线程中向coredata添加数据出错问题

ios 在多线程中向coredata添加数据出错问题

[self downloadImage:post];

/*
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:post];
[self.operationQueue addOperation:operation];
*/

如上图。如果我不用多线程添加数据,而是直接添加的话,就不会报错。

报错:CoreData: error: (1555) UNIQUE constraint failed: ZCACHEIMAGE.Z_PK


CoreData不是线程安全的,对于ManagedObject以及ManagedObjectContext的访问都只能在对应的线程上进行,而不能跨线程。

对于多个线程,每个线程使用自己独立的ManagedContext; 对于线程间需要传递ManagedObject的,传递ManagedObject ID,通过objectWithID或者existingObjectWithID来获取 ;对于持久化存储协调器(NSPersistentStoreCoordinator)来说,可以多个线程共享一个NSPersistentStoreCoordinator

建议使用FMDB来替代Core data


Coredata的多线程 建议使用iOS5.0之后的新api performBlockperformBlockAndWait, 而不是自己创建线程,并在线程中创建context管理.

【热门文章】
【热门文章】