一直以來,數(shù)據(jù)持久化使用的是sqlite,后半年的新項目選擇使用Apple的CoreData,果然如傳說的那樣再也沒有那些煩躁的sql語句了,測試階段也沒有發(fā)現(xiàn)很大的問題,結(jié)果上線crash 8成全是CoreData引起的。

經(jīng)過幾個版本迭代修復(fù) ,還是存在Crash,也是醉了,真的雞肋啊?。。?!

就Crash的情況做個簡單的總結(jié)
1 CoreData 線程不安全的。
CoreData:__65-[NSPersistentStoreCoordinatorexecuteRequest:withContext:error:]_block_invoke.547+8120
在多線程操作CoreData時就有了Crash風(fēng)險,建議拒絕在多線程頻繁操作CoreData,修復(fù)后Crash明顯減少了。
2 CoreData 操作一個實體時候,建議創(chuàng)建一個上下文,而不是多個上下文。多個上下文CoreData會發(fā)出警告,這種警告千萬不能忽略,要及時處理。這就是為啥CoreData設(shè)置成一個單利的原因。修復(fù)后明顯減少了。
warning: 'StampsInfo' (0x303f28fd0) from NSManagedObjectModel (0x302b6bb10) claims 'StampsInfo'.
還有一些警告 可以參考 https://forums.kodeco.com/t/multiple-warnings-when-running-unit-tests-in-sample-app/74860/8 的解決方案
2 CoreData:_PFCMT_SetValue+744
原因未知。推測是查詢太頻繁引起的,使用場景是funccaptureOutput(_output:AVCaptureOutput,didOutputsampleBuffer:
CMSampleBuffer,fromconnection:AVCaptureConnection)使用的,這個方法相機實時輸出里面用的。修復(fù)后,新版本沒出現(xiàn)。
3 CoreData: __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.541 + 8060
有問題的代碼
// MARK: get all cameras
/// 查詢相機列表數(shù)據(jù)
func queryCamerasInfo() -> [CameraInfo] {
let req = CameraInfo.fetchRequest()
// req.predicate = NSPredicate(format: "userId = %@",id)
let context = persistentContainer.viewContext
do {
let fetchedObjects = try context.fetch(req)
guard fetchedObjects.count > 0 else{return []}
return fetchedObjects
}
catch {}
return []
}
原因未知,改成如下:
func queryCamerasInfo() -> [CameraInfo] {
let req = CameraInfo.fetchRequest()
// req.predicate = NSPredicate(format: "userId = %@",id)
let context = persistentContainer.viewContext
// do {
// 這里查詢有閃退
let fetchedObjects = try? context.fetch(req)
if let fetchedObjects = fetchedObjects {
guard fetchedObjects.count > 0 else{return []}
return fetchedObjects
}
// }
// catch {}
return []
}
把try改成try? ,后續(xù)觀察一下。
4 CoreData: _PFObjectIDFastHash64 + 64

https://developer.apple.com/forums/thread/662240?page=2
https://forums.developer.apple.com/forums/thread/662240
原因很迷茫?。。。?/p>