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
^~~~~~~
모든 context.object (OBJECTID로)'주의하십시오 – Ladislav
나에게 좋아 보인다 당신. 아마도'existingObject (with :)' – jrturton