Balvansh Heerekar Balvansh Heerekar - 7 months ago 45
Swift Question

swift - EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) with Table View

Please bare with me as I am new to Swift. I am making an application which has nearly three buttons in its

Table View Cell
. One for sharing and the other two for other purpose. Before adding the sharing button code everything was working fine for me , the other two buttons were working great but now as soon as I wrote the function for sharing button I am getting an error in the
'Else'
part in the
IndexPath
statement. Here the cell leads to another view controller. Please help me understand where I am going wrong.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if segue.identifier == "showView"
{
let vc = segue.destinationViewController as UIViewController

let controller = vc.popoverPresentationController



//vc.preferredContentSize = CGSizeMake(265, 400)


if controller != nil
{
controller?.delegate = self
}


}
else{
//STotal.removeAll()
let indexpath: NSIndexPath = self.tableViews.indexPathForSelectedRow!
//error in the above line
//let DestViewController = segue.destinationViewController as! CellViewController

var newName : String
var newDetails : String
var newTime : String
var newTitle : String
var newImage : UIImage


newName = names[indexpath.row]
newTitle = breeds[indexpath.row]
newTime = timeDisp[indexpath.row]
newDetails = texty[indexpath.row] as! String
newImage = images[indexpath.row]!

SName = newName
STitle = newTitle
STime = newTime
SDetails = newDetails
SImages = newImage

// DestViewController.SName = newName
self.tableViews.deselectRowAtIndexPath(indexpath, animated: true)


}

}

Answer

I think your problem might be that when you click on the shared button, the cell does not go into the "selected" state and so the method you call

self.tableViews.indexPathForSelectedRow!

leads to a crash, because there is not selected row and you force unwrap it.

One possible solution might be something like this:

func didPressShareButton(sender: UITableViewCell) {
       let indexPath = tableView.indexPathForCell(sender)
       // prepare your DetailViewController now / show segue
}
Comments