从外部完成块 Parse 检索变量 Swift

Retrieving variable from outside completion block Parse Swift

我有一个包含 table 视图的应用程序。 table 视图由从 Parse 中提取的数据填充。为了获得我希望 TableView 填充的行数,我查询解析。

    var activeGamesCurrentUser = 0

    gamesQuery.countObjectsInBackgroundWithBlock({
            (count, error) -> Void in
            let countedInt = Int(UInt32(count))
            self.activeGamesCurrentUser = countedInt
        })

但是,当我尝试 return 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
     }

两件事 -

首先,始终访问块内的 class 属性,并弱引用自身。

第二个,完成模型更新后重新加载table。

weak var aBlockSelf = self

gamesQuery.countObjectsInBackgroundWithBlock({
            (count, error) -> Void in
            let countedInt = Int(UInt32(count))
            aBlockSelf.activeGamesCurrentUser = countedInt
            aBlockSelf.tableView.reloadData()
        })