2017-10-17 39 views
0

我需要在后台上传一个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 
^~~~~~~ 
+0

所有对我来说很好 – Ladislav

+0

注意'context.object(附:OBJECTID)'会生成一个新的对象您。你可能想要'existsObject(with:)' – jrturton

回答

0

这是一个有力的参考,但它是不安全的,如果接收器(对象)被删除的意思从它的上下文中,它将返回零。

只是我的意见,我会用,而不是保护一个if let声明:

func uploadObject(_ object: MyManagedObject, completion:()->()) { 
    // does the context has some strong reference here? 
    if let context = object.managedObjectContext { 

     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() 
      } 
     }) 
    } else { 
     completion() 
    } 
} 
+0

object.managedObjectContext()只是一个错字。固定。 –

+0

将'guard'改为'if let'没有意义。这只是增加了不必要的代码嵌套。 –

+0

对不起,那么:),那是我看到的唯一的问题......你正在保存私人MOC,这将推动它的变化,以其母MOC ...我并不是说它更好,只是两种不同的方式处理可选项。这两种代码块只有在设置了“上下文”时才会运行 –