ios - 从外部完成 block 检索变量 Parse Swift

标签 ios swift parse-platform tableview pfquery

我有一个包含表格 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/

相关文章:

iphone - 无法让 UITextField 自动收缩文本

ios - touchesBegan 在 Swift 中的用法

android - 解析 API 本地数据存储 - pinInBackground()

ios - 如何检查是否已设置类的所有可选成员?

ios - iPad:获取用户位置

ios - Swift:更新 CollectionView 单元格图像

ios - 如何保存 button.isEnabled = false 的状态?

ios - TableView Cell 中的 PFImageView 加载了错误的图像

javascript - 在 javascript 解释器环境中使用 parse

iOS Facebook sdk 打开相册选择和图像选择屏幕