【问题标题】:How to sync 2 async fetches in Parse?如何在 Parse 中同步 2 个异步获取?
【发布时间】:2015-04-25 13:30:24
【问题描述】:

所以我有一个 PFobject A,其中包含 2 个其他 PFobjects B C 作为值。当我构造我的本地对象 a 时,我需要两个对象 B C。所以首先我通过查询来获取 a:

let query = PFQuery(className: "A")
query.getObjectInBackgroundWithId("1", block: { (a, error) -> Void in

然后我从 a 得到 b 和 c

var b = a!["B"] as! PFObject
var c = a!["C"] as! PFObject

然后我需要分别获取 b 和 c 对象

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in

问题是,获取方法是异步的,如果我将它们放在同一个线程中,我将无法保证最终同时获取它们。

一种解决方案是将获取嵌套在回调中,以便一旦完成一次获取,它将启动另一个。

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in
    c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in
        println(fetchedB)
        println(fetchedC) // Now they have values
        var myA = A(validB: fetchedB, validC: fetchedC) // Construction can continue

但是如果需要更多的对象,就会变成嵌套中的嵌套。喜欢:

b.fetchInBackgroundWithBlock({ (fetchedB, error) -> Void in
    c.fetchInBackgroundWithBlock({ (fetchedC, error) -> Void in
        d.fetchInBackgroundWithBlock({ (fetchedD, error) -> Void in
            e.fetchInBackgroundWithBlock({ (fetchedE, error) -> Void in

但是 b、c、d 和 e 并不相互依赖 - 在单独的线程上获取它们应该是完美的!

那么有没有办法让回调在主线程中的某个时刻相互等待,以确保所有对象都被获取?

谢谢!

【问题讨论】:

    标签: ios swift parse-platform


    【解决方案1】:

    在第一个 PFQuery 上使用 includeKey() 方法告诉 parse 在执行查询时获取 B 类和 C 类。 Relevant documentation for includeKey

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2019-08-19
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      相关资源
      最近更新 更多