gpt4 book ai didi

解析查询后 Swift 数组为空 - 完成处理程序?

转载 作者:行者123 更新时间:2023-11-30 14:06:03 26 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

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

关于解析查询后 Swift 数组为空 - 完成处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32379820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com