我經歷了很多有關CoreData的discutions和主題,但我一直都遇到同樣的問題。CoreData在串行隊列中讀取時發生崩潰
下面是上下文:我有一個應用程序必須對CoreData進行多次訪問。爲了簡化起見,我決定聲明專門用於訪問的串行線程(用於讀取的queue.sync,用於保存的queue.async)。我有一個嵌套三次的結構,並重新創建整個結構,我取subSubObject,然後子對象,最後對象
但有時(如「對象」的1/5000娛樂)上擷取結果CoreData崩潰,不帶堆棧跟蹤,沒有崩潰日誌,只有 EXC_BAD_ACCESS(代碼1)
對象是不是原因,因爲所有的訪問都是在同一個線程這是一個完成的崩潰是怪異系列線程
如果有人能幫助我,我將非常感激!
下面的代碼的結構:
private let delegate:AppDelegate
private let context:NSManagedObjectContext
private let queue:DispatchQueue
override init() {
self.delegate = (UIApplication.shared.delegate as! AppDelegate)
self.context = self.delegate.persistentContainer.viewContext
self.queue = DispatchQueue(label: "aLabel", qos: DispatchQoS.utility)
super.init()
}
(...)
public func loadObject(withID ID: Int)->Object? {
var object:Object? = nil
self.queue.sync {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Name")
fetchRequest.predicate = NSPredicate(format: "id == %@", NSNumber(value: ID))
do {
var data:[NSManagedObject]
// CRASH HERE ########################
try data = context.fetch(fetchRequest)
// ###################################
if (data.first != nil) {
let subObjects:[Object] = loadSubObjects(forID: ID)
// Task creating "object"
}
} catch let error as NSError {
print("CoreData : \(error), \(error.userInfo)")
}
}
return object
}
private func loadSubObjects(forID ID: Int)->[Object] {
var objects:[Object] = nil
self.queue.sync {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Name")
fetchRequest.predicate = NSPredicate(format: "id == %@", NSNumber(value: ID))
do {
var data:[NSManagedObject]
// OR HERE ###########################
try data = context.fetch(fetchRequest)
// ###################################
if (data.first != nil) {
let subSubObjects:[Object] = loadSubObjects(forID: ID)
// Task creating "objects"
}
} catch let error as NSError {
print("CoreData : \(error), \(error.userInfo)")
}
}
return objects
}
(etc...)
可能重複[如何在正確的隊列上初始化ManagedObjectContext?](http://stackoverflow.com/questions/41988409/how-to-init-managedobjectcontext-on-the-right-queue) – 2017-03-01 01:35:20
檢查出我的在重複中回答。您不應該爲Core Data使用自定義線程。您可以將其添加到您的項目,以瞭解您將來何時違反線程:http://stackoverflow.com/questions/31391838/making-com-apple-coredata-concurrencydebug-1-work – 2017-03-01 01:35:39