我需要在后台上传一个CoreData
对象到API服务器。为此,我创建一个新的私有上下文作为主要上下文的子项,并对其执行perform()
。我使用此上下文从对象获取JSON数据,并在上传后将一些数据写入对象。Swift:在后台同步CoreData对象
它似乎一切正常,但我有一些疑虑。
下面是一个简单的例子,它显示了这种情况。上下文在第二个函数中是否有强有力的参考?我应该在某处保留一些有关我的新环境的强烈参考吗?
// ViewController.swift
func uploadObject(_ currentObject: MyManagedObject) {
// we are in the main thread, go to another thread
let objectId = currentObject.objectID
let context = getNewPrivateContext() // child context of the main context
context.perform {
if let object = context.object(with: objectId) as? MyManagedObject {
SyncManager.shared.uploadObject(_ object: object, completion: {
// ... update UI
})
}
}
}
// SyncManager.swift
func uploadObject(_ object: MyManagedObject, completion:()->()) {
// does the context has some strong reference here?
guard let context = object.managedObjectContext { completion(); return }
let params = getJson(with: object)
// ... prepare url, headers
Alamofire.request(url, method: .put, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON(completionHandler: { (response) in
// ... parse the response
context.perform {
// ... write some data to the Core Data and save the context
completion()
}
})
}
编辑
而且我的疑惑被一个LLDB问题的支持:
(lldb) po context
error: <EXPR>:3:1: error: use of unresolved identifier 'context'
context
^~~~~~~
所有对我来说很好 – Ladislav
注意'context.object(附:OBJECTID)'会生成一个新的对象您。你可能想要'existsObject(with:)' – jrturton