fatal error: Array index out of range with Parse.com

523 Views Asked by At

I have an application with Swift 2 and Parse.com. I added the UISearchController, and when I use it, the application is crash. And it shows an error "fatal error: Array index out of range".

There is an error in the string "if var pfFiltered = dataForSearchController?[indexPath.row]" is EXC_BAD_INSTRUCTION when I touch in the search bar.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
    var searchText = searchController.searchBar.text

    let cellIndentifier: String = "NewsCell"

    var cell: ParseTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as? ParseTableViewCell

    if searchController.active == false {
        if (cell == nil) {
            cell = ParseTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIndentifier)
        }

        if let pfObject = object {
            //cell?.textLabel?.text = pfObject["textNews"] as? String
            cell?.labelNameText?.text = pfObject["nameNews"] as? String // name
            cell?.labelDataText?.text = pfObject["dateNews"] as? String // data
            cell?.labelText = pfObject["textNews"] as? String
            cell?.labelURLNews = pfObject["urlNews"] as? String // link on a site with news

            var imageFromParse = object?.objectForKey("imageNews") as? PFFile
            imageFromParse?.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
                var image: UIImage! = UIImage(data: imageData!)!
                cell?.imageViewCell.image = image
            })
        }
    } else {
        if var pfFiltered = dataForSearchController?[indexPath.row] {
            cell?.labelNameText?.text = pfFiltered["nameNews"] as? String
            cell?.labelDataText?.text = pfFiltered["dateNews"] as? String
            cell?.labelText = pfFiltered["textNews"] as? String
            cell?.labelURLNews = pfFiltered["urlNews"] as? String

            var imageFromFilteredParse = object?.objectForKey("imageNews") as? PFFile
            imageFromFilteredParse?.getDataInBackgroundWithBlock({ (imageDataTwo: NSData?, error: NSError?) -> Void in
                var imageTwo: UIImage = UIImage(data: imageDataTwo!)!
                cell?.imageViewCell.image = imageTwo
            })
        }
    }
    return cell
}
1

There are 1 best solutions below

0
On BEST ANSWER
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var query: PFQuery = PFQuery(className: "NewsNow")
    if self.dataForSearchController == nil {
        return objects?.count ?? 0
    } else {
        return dataForSearchController?.count ?? 0
    }
}