我有一个包含表格 View 的应用程序。 TableView 由从 Parse 提取的数据填充。为了获取我想要填充 TableView 的行数,我查询解析。
var activeGamesCurrentUser = 0
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
self.activeGamesCurrentUser = countedInt
})
但是,当我尝试返回 activeGamesCurrentUser 的行数时,它始终为 0,因为变量不会在完成 block 之外更新。如果我在 block 内打印“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 的弱引用来访问 block 内的类属性。
第二,完成模型更新后重新加载表格。
weak var aBlockSelf = self
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
aBlockSelf.activeGamesCurrentUser = countedInt
aBlockSelf.tableView.reloadData()
})
关于ios - 从外部完成 block 检索变量 Parse Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33405083/