【发布时间】: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是异步的。如果您 println() 也为每种情况使用不同的数字,您会发现它们不是按照您认为的顺序调用的。
标签: swift parse-platform block completionhandler