
[英]get the value of variable outside of completion block from closure in swift 4
[英]Retrieving variable from outside completion block Parse Swift
我有一个包含表格视图的应用程序。 表格视图由从Parse提取的数据填充。 若要获取要填充TableView的行数,请查询解析。
var activeGamesCurrentUser = 0
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
self.activeGamesCurrentUser = countedInt
})
但是,当我尝试返回activeGamesCurrentUser的行数时,它始终为0,因为变量不会在完成块之外更新。 如果我在块内打印“ countedInt”,则它是一个大于0的数字。
我不想解决这样的问题:
var count = gamesQuery.countObjects()
activeGamesCurrentUser = count
其原因是因为“ countObjects()”是同步的,并且将永远在前台继续运行。 关于此问题的任何帮助将不胜感激。
编辑:
这是完整的方法:
var activeGamesCurrentUser = 0
func getRowNumber() {
if PFUser.currentUser() != nil && finished == true {
currentUserObjectId = PFUser.currentUser()?.objectId
let currentUser = PFUser.currentUser()
let challengedQuery = PFQuery(className: "Games")
challengedQuery.whereKey("challenged", equalTo: currentUserObjectId)
let challengerQuery = PFQuery(className: "Games")
challengerQuery.whereKey("challenger", equalTo: (currentUser?.objectId)!)
let gamesQuery = PFQuery.orQueryWithSubqueries([challengedQuery, challengerQuery])
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
self.activeGamesCurrentUser = countedInt
})
}
override func viewDidLoad() {
super.viewDidLoad()
getRowNumber()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activeGamesCurrentUser
}
几件事-
首先 ,始终使用对self的弱引用来访问块内的类属性。
第二 ,完成模型更新后,重新加载表。
weak var aBlockSelf = self
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
aBlockSelf.activeGamesCurrentUser = countedInt
aBlockSelf.tableView.reloadData()
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.