在 cellForRowAtIndexPath 中使用 PFQuery

Using PFQuery inside cellForRowAtIndexPath

我在考虑PFQuery

我正在开发一个向用户显示提要的应用程序,它还会为每个 Post(例如 Facebook 应用程序或 Instagram 应用程序)显示一个“赞”计数器。

所以在我的 PFQueryTableViewController 中我有我的主要查询,它基本上显示了所有 Posts:

override func queryForTable() -> PFQuery {
    let query = PFQuery(className: "Noticias")
    query.orderByDescending("createdAt")   
    return query
}

然后我使用另一个查询来计算另一个 Class 在 Parse 中的点赞数,其中包含所有点赞。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
    var cell = tableView.dequeueReusableCellWithIdentifier("FeedCellIdentifier") as! FeedCell!
    if cell == nil {
        cell = FeedCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCellIdentifier")
    }

    let query2 = PFQuery(className:"commentsTable")
    query2.whereKey("newsColumn", equalTo: object!)
    query2.findObjectsInBackgroundWithBlock {
        (objectus: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            let quantidade = objectus!.count

            let commentQuantidade = String(quantidade)

            cell.comentariosLabel.text = commentQuantidade
        } else {
            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }
    }

这种编码方式有效,我实现了我想要的,但是!我知道我正在重用单元格,我知道每次出现单元格时都会调用这段代码。

我知道这些事实:

  1. 每次滚动表格视图时,都会向 Parse Cloud 发送大量查询请求

  2. 例如,当我滚动表格视图时,可能会看到值发生变化,因为我正在重复使用单元格 post 具有我以前的单元格的值并且然后使用新查询刷新它,这有效但不利于用户体验。

所以,我的主要疑问是,这种编码方式是否正确?我认为不是,我只是想要另一个观点或想法。

谢谢。

编辑 1

正如我所说,我已将我的计数方法更新为 countObjectsInBackgroundWithBlock 而不是 findObjectsInBackgroundWithBlock 但我无法将查询移动到 ViewDidLoad,因为我使用 object 来检查每个 Post 有多少条评论。

编辑 2 我嵌入了查询以计算每个 post 的评论数并打印结果,现在我认为我的代码比以前的版本更好,但我无法将结果传递给标签,因为我收到错误消息:

Use of unresolved identifier 'commentCount'

我正在阅读一些关于 Struct

的文档

下面是我更新后的代码:

import UIKit
import Social

class Functions: PFQueryTableViewController, UISearchBarDelegate {

override func shouldAutorotate() -> Bool {
    return false
}

var passaValor = Int()
let swiftColor = UIColor(red: 13, green: 153, blue: 252)
struct PostObject{
    let post : PFObject
    let commentCount : Int
}

var posts : [PostObject] = []


// Initialise the PFQueryTable tableview
override init(style: UITableViewStyle, className: String!) {
    super.init(style: style, className: className)
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    // The className to query on
    self.parseClassName = "Noticias"

    // The key of the PFObject to display in the label of the default cell style
    self.textKey = "text"

    // Uncomment the following line to specify the key of a PFFile on the PFObject to display in the imageView of the default cell style
    self.imageKey = "image"

    // Whether the built-in pull-to-refresh is enabled
    self.pullToRefreshEnabled = true

    // Whether the built-in pagination is enabled
    self.paginationEnabled = true

    // The number of objects to show per page
    self.objectsPerPage = 25
}

// Define the query that will provide the data for the table view

override func queryForTable() -> PFQuery {
    let query = super.queryForTable()

    return query
}



override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    loadObjects()
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func viewDidLoad() {
    super.viewDidLoad()
    // navigationBarItems()


    let query = PFQuery(className:"Noticias")
    query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in

        // The find succeeded.
        print("Successfully retrieved \(objects!.count) scores.")
        // Do something with the found objects
        if let objects = objects {
            for object in objects {
                let queryCount = PFQuery(className:"commentsTable")
                queryCount.whereKey("newsColumn", equalTo: object)
                queryCount.countObjectsInBackgroundWithBlock {
                    (contagem: Int32, error: NSError?) -> Void in
                    let post = PostObject(object, commentCount:commentCount)
                    posts.append(post)
                    print("Post \(object.objectId!) has \(contagem) comments")
                }
                self.tableView.reloadData()
            }
        }
    }

    //Self Sizing Cells
    tableView.estimatedRowHeight = 350.0
    tableView.rowHeight = UITableViewAutomaticDimension


}



// Define the query that will provide the data for the table view

//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell = tableView.dequeueReusableCellWithIdentifier("FeedCellIdentifier") as! FeedCell!
if cell == nil {
    cell = FeedCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCellIdentifier")
}

cell?.parseObject = object

if let assuntoNoticia = object?["assunto"] as? String {
    cell?.assuntoNoticia?.text = assuntoNoticia
}


if let pontos = object?["pontos"] as? Int {
    let pontosPosts = String(pontos)
    cell?.pontosLabel?.text = String(pontosPosts)
}


if let zonaLabel = object?["zona"] as? String {
    cell?.zonaLabel?.text = zonaLabel
}


if let criticidade = object?["criticidade"] as? String {
    if criticidade == "Problema"{

        cell.criticidadeNoticia.backgroundColor = UIColor.redColor()
    } else {
        cell.criticidadeNoticia.backgroundColor = UIColor.greenColor()
    }
}

return cell
}
}

以及打印的结果:

Successfully retrieved 5 scores.

Post wSCsTv8OnH has 4 comments

Post LbwBfjWPod has 0 comments

Post fN4ISVwqpz has 0 comments

Post 1rXdQr2A1F has 1 comments

Post eXogPeTfNu has 0 comments

在表视图中显示信息之前,您应该进行查询。

更好的做法是在视图加载时查询所有数据,将其保存到模型中,然后在 table 视图滚动中从中读取数据。处理查询时,您可以显示下载指示器或占位符数据。查询完成后,您将调用 tableView.reloadData()

您可以像这样创建一个新变量来完成此操作:

 var cellModels : [PFObject] = []

在你的 query2.findObjectsInBackgroundWithBlock:

 for object in objectus{
   self.cellModels.append(object)
 }
 self.tableView.reloadData()

cellForRowAtIndexPath中:

let model = cellModels[indexPath.row]
// configure cell according to model
// something like cell.textLabel.text = model.text

P.S 如果你只需要获取对象的数量,你应该看看方法 countObjectsInBackgroundWithBlock。因为如果有很多例如评论 findObjectsInBackgroundWithBlock 将 return 最多 1000 个对象,但您仍然不会下载整个对象,只有一个数字,这将加快查询速度并节省用户的手机计划。

更新:此外,如果您需要存储评论数量,您可以像这样创建简单的struct

struct PostObject{
 let post : PFObject
 let commentCount : Int
}

var posts : [PostObject] = []

当你查询你的帖子时,你循环接收到的对象并填充 posts 数组。

for object in objects{
  // create countObjectsInBackgroundWithBlock query to get comments count for object
  // and in result block create
  let post = PostObject(object, commentCount:commentCount)
  posts.append(post)

} 
tableView.reloadData()

cellForRowAtIndexPath中:

let post = posts[indexPath.row]
cell.postCountLabel.text = String(post.commentCount)
// configure cell accordingly