Array index out of range on refresh

1k views Asked by At

I have a Posts class that I am querying in a UITableViewController using Parse as my backend.

In my viewDidAppear I call my loadData() function. And then I have a var refresher = UIRefreshControl() that is responsible for my refresh() function.

After a few time reloading the data I get a a fatal error: Array index out of range and the following line of code highlighted which is in my cellForRowAtIndexPath.

enter image description here

What was interesting is when I printed out what was in my index path using println(drive), all the posts were there. But then there were instances where some posts appeared twice then the app would crash.

timelineData.removeAll(keepCapacity: false)

I thought that having this should clear everything so I am not sure why this is happening.

Here is my code for my refresh function.

func refresh()
{

    println("refresh table from pull")

    timelineData.removeAll(keepCapacity: false)

    var findItemData:PFQuery = PFQuery(className:"Posts")

    findItemData.addDescendingOrder("createdAt")

    findItemData.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]? , error:NSError?) -> Void in
        if error == nil
        {
            self.timelineData = objects as! [PFObject]
            self.newsFeedTableView.reloadData()

        }

    }
    self.refresher.endRefreshing()


}

I tried using Parse's query.cachePolicy but that didn't matter because the crash kept happening. https://parse.com/docs/ios/guide#queries-querying-the-local-datastore

I also thought it was because I have Parse.enableLocalDatastore() but still no luck.

I do call my other function loadData in my viewDidAppear as mentioned earlier, not sure if this might be the problem, but I don't know how to check for data when there is an update. Still not sure if this is the source of the problem.

EDIT 1

I have attached my timelinedata count in several functions. Second image is when I print the count in my cellForRowIndexPath enter image description hereenter image description here

1

There are 1 answers

2
Miknash On BEST ANSWER

Try to:

findItemData.findObjectsInBackgroundWithBlock{
    (objects:[AnyObject]? , error:NSError?) -> Void in
    if error == nil
    {
        timelineData.removeAll(keepCapacity: false)
        self.timelineData = objects as! [PFObject]
        self.newsFeedTableView.reloadData()
    }
} 

It could happen that you have inconsistent data before you actually populate your list. This way you will have your data if some kind of error occurs, so you are safe from that point as well.