【问题标题】:swift 2 parse data from findObjectsInBackgroundWithBlockswift 2 从 findObjectsInBackgroundWithBlock 解析数据
【发布时间】:2015-11-08 20:02:04
【问题描述】:

我这里有一个带有 parse.com 代码的 swift 2

问题是代码在 //1 之前打印 // 2 这会造成问题,我无法在其他方法或其他地方使用该数组 这是代码

 var myStudent:Student = Student ()

        let query = PFQuery(className: "Students")
                query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error:NSError?) -> Void in

                    var the_array = objects as! AnyObject

                    for i in 0...the_array.count-1
                    {

                myStudent.NameStudent = the_array[i].valueForKey("name") as! String
                self.myStudentsArray.append(myStudent)
                        print(self.myStudentsArray.count) //1

            }
        }
        print(self.myStudentsArray.count) //2

【问题讨论】:

  • 这是有意的。 findObjectsInBackgroundWithBlock 异步工作。考虑将您的设计从被动(等待返回值)更改为主动(在完成块中进行更改/更新)。
  • 我知道原因,并且使用 findObjectsInBackgroundWithBlock 这么快的代码我的问题是这段代码有什么解决方案吗?

标签: swift parse-platform


【解决方案1】:

这是因为findObjectsInBackgroundWithBlock 在后台线程上异步运行。

解决方案是在闭包中调用任何需要准确 .count 的函数,这样您就可以确保获得正确的 Array.count。

var myStudent:Student = Student ()

    let query = PFQuery(className: "Students")
            query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error:NSError?) -> Void in

                var the_array = objects as! AnyObject

                for i in 0...the_array.count-1
                {

            myStudent.NameStudent = the_array[i].valueForKey("name") as! String
            self.myStudentsArray.append(myStudent)
                    print(self.myStudentsArray.count) //1
          //Call any function that needs the students count here. This would 
         //be the only way you can guarantee you will get the correct count within the closure.

        }
    }
    print(self.myStudentsArray.count) //2

这是一个关于Grand Central Dispatch (GCD) - RayWenderlich 的很棒的教程。如果需要 print 2 最后执行,请尝试在同一个闭包中实现代码。

您也可以参考堆栈答案Synchronous vs Asynchronous。问题是关于 Objective C 的,但是原理和 Swift 是一样的。

另外,如果你想了解 Swift 中的并发,可以参考之前的 Stack 回答 How to do multithreading, concurrency or parallelism in iOS Swift

【讨论】:

  • 我知道原因,并且使用 findObjectsInBackgroundWithBlock 的代码比 findObjects 快,我的问题是这段代码有什么解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多