我一直在刷新數據或在啓動時發生50%的時間(從服務中獲取並保存在coreData中)時出現此運行時錯誤。我已經瀏覽了幾乎所有關於這個問題的解決方案,但其中大部分都在Obj-C中,但我是iOS新手,並且使用了swift。我有大約20個表,並且都使用相同的上下文。由於NSManagedObjectContextObjectsDidChangeNotification導致的運行時錯誤
下面是我的代碼:
public class ServiceCalls : NSManagedObject {
/*
class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let moc = NSManagedObjectContext(concurrencyType:.mainQueueConcurrencyType)
let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateMOC.parent = moc
privateMOC.perform({
do {
try privateMOC.save()
} catch {
fatalError("Failure to save context: \(error)")
}
})
return appDelegate.persistentContainer.viewContext
}
*/ // tried this but didn't work
class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
這是我如何使用它,下面是在數據庫中保存的數據的一個例子。
class func SaveCustomerContacts(name : String,id : String){
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "AllCustomerContacts_Tbl", in: context)
let newDoc = NSManagedObject(entity: entity!, insertInto: context)
newDoc.setValue(name, forKey: "contactName")
newDoc.setValue(id, forKey: "id")
//save the object
do {
try context.save()
print("saved Customer contacts in Database yayy!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
這被拋出完整的異常:
[error] error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2017-07-31 16:09:20.908 Sales CRM[5846:202190] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack:
您是否有任何fetchedResultsController設置?你有任何關於NSManagedObjectContextObjectsDidChangeNotification的觀察者嗎? –
@JonRose不,我沒有在任何地方使用NSManagedObjectContextObjectsDidChangeNotification。並且也沒有fetchedResultsController設置。 –
有兩個問題:(1)你是否在任何地方觀察過'NSManagedObjectContextObjectsDidChangeNotification'? (2)這個代碼在哪個隊列上運行? –