【问题标题】:Swift Array is Empty After Parse Queries - Completion Handler?解析查询后 Swift 数组为空 - 完成处理程序?
【发布时间】:2015-09-03 15:29:09
【问题描述】:

我不明白为什么在使用块查询后数组变为空。我做了一些研究,这很可能是因为我需要一个完成处理程序,但我不知道在这种情况下如何实现它。我可以在方法完成之前添加一个活动指示器吗?

var usernamesFollowing = [""]
var useridsFollowing = [""]

func refresh(completion: (Bool)){

    //find all users following the current user
    var query = PFQuery(className: "Followers")
    query.whereKey("following", equalTo: PFUser.currentUser()!.objectId!)
    query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

        if error == nil {
            //remove all from arrays
            self.usernamesFollowing.removeAll(keepCapacity: true)
            self.useridsFollowing.removeAll(keepCapacity: true)

            //get all userIds of following current user and add to useridsFollowing array
            if let objects = objects {

                for userId in objects {

                    var followerId = userId["follower"] as! String
                    self.useridsFollowing.append(followerId)

                    //get usernames from followerId and add to usernamesFollowing array
                    var query = PFUser.query()
                    query!.whereKey("objectId", equalTo: followerId)
                    query!.findObjectsInBackgroundWithBlock({ (objects2, error) -> Void in

                        if let objects2 = objects2 {
                            for username in objects2 {
                                var followerUsername = username["username"] as! String
                                self.usernamesFollowing.append(followerUsername)
                            }
                        }
                        //WORKS. usernamesFollowing array is now full.
                        println(self.usernamesFollowing)
                    })
                    //BROKEN. usernamesFollowing array is now empty outside of block.
                    println(self.usernamesFollowing)

                }

            }
        }
        //WORKS. useridsFollowing is now full.
        println(self.useridsFollowing)
    })

    //BROKEN. usernamesFollowing is now empty outside of block.
    println(self.usernamesFollowing)
}

【问题讨论】:

  • 这是因为findObjectsInBackgroundWithBlock 是异步的。如果您 p​​rintln() 也为每种情况使用不同的数字,您会发现它们不是按照您认为的顺序调用的。

标签: swift parse-platform block completionhandler


【解决方案1】:

详细说明 Larme 的观点 - 异步方法立即返回,并将工作分派到另一个队列中。为了说明这一点,请考虑您的两个 println 语句:

println(self.usernamesFollowing) //1. inside async fetch closure
println(self.usernamesFollowing) //2. outside async fetch closure

异步方法将获取您的闭包并将其分派到不同的队列。这样做之后,它会立即返回,并继续执行您的代码,该代码会立即转到您的 2nd println 语句。在这种情况下,您的第二个 println 语句实际上将在您的第一个之前打印。

如果可能,请在块内执行所有数据操作。它将为您节省大量工作。如果您必须卸载块外的对象,请考虑使用NSOperations,它非常适合处理这种类型的场景。

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多