Trenton Tyler
Trenton Tyler

Reputation: 83

Parse.com query not working properly

I am trying to filter the posts based on their profile. For instance, when I go to my profile I only want to see my posts, not all the posts in my database. I attempted to make a filter for that but the code below does not seem to work and I am unsure as to why that is. It may be something obvious but I can not seem to pinpoint the issue, any ideas? I have attached a picture of the database to further assist anybody.

The code runs perfectly fine it just does not filter the usernames.

enter image description here

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var user = PFUser.currentUser()?.username!

    let bucketCellObj = tableView.dequeueReusableCellWithIdentifier("bucket", forIndexPath: indexPath) as! BucketTableViewCell

    var query = PFQuery(className: "Bucket")
    query.whereKey("creator", equalTo: user!)
    query.findObjectsInBackgroundWithBlock { (PFObject, error) -> Void in
        if error == nil {
            bucketCellObj.bucketname.numberOfLines = 0
            bucketCellObj.username.text = self.bucketsArray[indexPath.row]["creator"] as? String
            bucketCellObj.bucketname.text = self.bucketsArray[indexPath.row]["name"] as? String
            bucketCellObj.selectionStyle = .None
        } else {
            print("ERROR")
        }
    }
    return bucketCellObj
}

Upvotes: 0

Views: 40

Answers (1)

luk2302
luk2302

Reputation: 57184

What you are doing here might work under some circumstances but will certainly bite you at some point.

What your code does:

  • show some arbitrary number of cells - probably based on self.bucketsArray.count or something similar
  • in each cell creation, run a parse query
  • when the query returns, customize the already displayed cell accordingly - without any usage of the requested query response

That will cause problems for a couple of reasons:

  • you perform too many requests, each cell requests some data, each new displayed cell requests its own data again
  • you display the old data in the cell until the new data is fetched which could take a few seconds due the amount of requests
  • you could encouter a problem where you requests some data for a cell, that cell moves off-screen, gets reused, then the first query returns, still holds the reference to it and will therefore display wrong data

How it can be solved

Do not requests the data in the cellForRowAtIndexPath.
Request the data once in viewDidLoad or similar. as soon as the data gets returned, parse it and initiate a tableView.reload().
In the cellForRowAtIndexPath make use of the already retrieved data, do not perform anymore async tasks.

Upvotes: 1

Related Questions