[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
或者existingObjectWithI
D来获取 ;对于持久化存储协调器(NSPersistentStoreCoordinator)
来说,可以多个线程共享一个NSPersistentStoreCoordinator
建议使用FMDB来替代Core data
Coredata的多线程 建议使用iOS5.0之后的新api performBlock
与 performBlockAndWait
, 而不是自己创建线程,并在线程中创建context管理.