solenoid
solenoid

Reputation: 1022

Calling delegate method from another class/method (specifically didSelectRowAtIndexPath)

Say I have a tableViewController and the following:

class tablVC: UITableViewController {
...
func thingsToDo() {
doSomeGenericStuff(indexPath: anIndexPath, targetTableView: self.tableView [, the Delegate: UITableViewDelegate]) //the part in parentheses is explained blow
}
...
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// do stuff
}
...

}

doSomeGenericStuff() is a method outside of the class due to having a bunch of fairly different tableViewControllers that all want use this method.

What I really want to do from this method is call:

tableView(TableView: UITableView, didSelectRowAtIndexPath: NSIndexPath) 

I have had it set like the following, and I have also tried passing it the delegate directly as well.

func doSomeGenericStuff(indexPath: NSIndexPath, targetTableView: UITableView [, theDelegate: UITableViewDelegate]) {
...
//call didSelectRowAtIndexPath here
...
}

With the code in parentheses I can get the autocomplete, but the following code crashes.

theDelegate.tableView!(targetTableView, didDeselectRowAtIndexPath: indexPath)

Is there a way to get this to work in any fashion?

UPDATE: The error

2016-06-12 12:49:12.390 AppName[14221:3670062] -[AppName.tableVC tableView:didDeselectRowAtIndexPath:]: unrecognized selector sent to instance 0x14c6ea370
2016-06-12 12:49:12.392 AppName[14221:3670062] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.tableVC tableView:didDeselectRowAtIndexPath:]: unrecognized selector sent to instance 0x14c6ea370'

Upvotes: 0

Views: 493

Answers (1)

solenoid
solenoid

Reputation: 1022

I needed to be passing the tableViewController, not the tableView.

I guess I will leave this up here as a reminder about scope, and to remind myself to pay attention to it, and something about public shaming.

            targetTableViewController.tableView.delegate?.tableView!(targetTableViewController.tableView, didSelectRowAtIndexPath: indexPath)

Upvotes: 1

Related Questions