我不明白为什么在使用块查询后数组变空。我做了一些研究,这很可能是因为我需要一个完成处理程序,但在这种情况下我无法弄清楚如何实现它。我可以在方法完成之前添加活动指示器吗?
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)
}
答案 0 :(得分:0)
详细说明Larme的观点 - 异步方法立即返回,并将工作分派到另一个队列中。要将其置于上下文中,请考虑您的两个char
语句:
char[] array = new char[8];
for (int x = 0; x < 8; x++)
{
array[x] = (char) 97; // Or whatever
}
String name = new String(array);
System.out.println(name);
异步方法将关闭并将其分派到不同的队列。完成后,它会立即返回,并继续执行您的代码,然后立即转到第二 println
语句。在这种情况下,您的第二个println(self.usernamesFollowing) //1. inside async fetch closure
println(self.usernamesFollowing) //2. outside async fetch closure
语句实际上会在您的第一个之前打印出来。
如果可能,请在块内完成所有数据操作。它可以为您节省大量的工作。如果必须卸载块外部的对象,请考虑使用println
,它可以完美地处理这种类型的场景。