0

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

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)
}
4

1 回答 1

0

详细说明 Larme 的观点 - 异步方法立即返回,并将工作分派到另一个队列中。为了把它放在上下文中,考虑你的两个println陈述:

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

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

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

于 2015-09-03T21:58:16.083 回答