计数在PFTableQueryViewController中找到的对象



我正在计算PFQueryTableViewController中发现的对象的数量。

我已经尝试过使用

override func queryForTable() -> PFQuery {
    let query = PFQuery(className: self.parseClassName!)
    query.whereKey("member", equalTo: memberId!)
    let count = query.countObjectsInBackground()
    label.text = "(count)"

    return query
}

但是我的应用程序会崩溃。

编辑:

问题不在于查询和计算对象。问题是使用queryForTable将我的查询传递给PFQueryTableViewControllercellForRowAtIndexPath

cellForRowAtIndexPath看起来像这样:

   override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
    let cell:DetailApplicantCell = self.table.dequeueReusableCellWithIdentifier("reuseIdentifier") as! DetailApplicantCell
    if let name = object?.objectForKey(self.textKey!) as? String{
    cell.nameLbl.text = name
    }
    cell.groupImage.image = UIImage(named: "People.png")
    if let imageFile = object?.objectForKey(self.imageKey!) as? PFFile{
    cell.groupImage.file = imageFile
    cell.groupImage.loadInBackground()
    }
    return cell
}

注意,这不是默认的cellForRow

尝试使用query.findObjectsInBackgroundWithBlock方法并获得响应对象的size()

        let query = PFQuery(className: self.parseClassName!)
        query.whereKey("member", equalTo: memberId!)
        query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]?, error: NSError?) -> Void in
                if error == nil {
                    let count = objects.size()
                    label.text = "(count)"
                    if let object = objects as? [PFObject] {
                    }
                } else {
                    // Log details of the failure
                    print("Error: (error!)")
                }
         }

在两个地方强制展开,使用if let:

func queryForTable() -> PFQuery? {
   if let parseClass = self.parseClassName {
      let query = PFQuery(className: parseClass)
      if let id = memberId {
         query.whereKey("member", equalTo: id)
      }
      let count = query.countObjectsInBackground()
      label.text = "(count)"
      return query
   }
   return nil
}

然后像这样使用函数:

if let query = queryForTable() {
    //your query related code here.
}

而不是做第二个PFQuery,我发现了一个更好的方法,使用PFQueryTableViewController的方法,像这样:

    override func objectsDidLoad(error: NSError?) {
    super.objectsDidLoad(error)
    print("objectsDidLoad")
        if let results = self.objects{
        print("objectsFound")
        self.groupsCountLbl.text = "(results.count)"
        self.groupsCountLbl.fadeIn()
    }
}

VC有一个属性objects,一个AnyObject?的数组。使用objectsDidLoad函数确定时间,所有内容都被加载。

最新更新