Delegates, can't get my head around them

筅森魡賤 提交于 2019-11-28 20:57:27

In Cocoa, objects almost always identify themselves when calling a delegate method. For example, UITableView passes itself as the first parameter of the delegate message when calling it:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

If you wanted the same delegate to handle multiple UITableViews, then you just need a some conditional on the tableView object passed to the method:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.myFirstTableView) {
        // do stuff
    } else if (tableView == self.mySecondtableView) {
        // do other stuff
    }
}

}

If you don't want to compare the object pointers directly, you can always use the tag property to uniquely identify your views.

Usually, if you have a delegate method that might have to receive messages from many different objects, you simply have the calling object pass itself to the delegate in the message (method call).

For example, if you wanted a delegate method to extract the text from a tableviewcell's label, the method definition would look something like:

-(void) extractTextFromLabelOfTableCell:(UITableViewCell *) theCallingCell{
...
NSString *extractedText=theCallingCell.textLabel.text;
}

You would call the method from a tableviewcell thusly:

[delegate extractTextFromLabelOfTableCell:self];

Each instance of the tableviewcell would send itself to the delegate and the delegate would extract that instance's text. In this way, a single delegate object could handle an arbitrarily large number of cells.

A delegate is a way of adding behaviors to a class without subclassing or for attaching a controller to a class.

In the table view example you gave, the delegate is extending or controlling the table, not the cell. The table is designed to have a controller, the cell is not. This design choice is why you can't specify cell-specific delegates.

However, delegate methods will always announce the source object (the one to which the delegate is attached) and relevant parameters (like the cell involved) so you should always be able to handle the action fully.

In your case, if you have a cell and you would like the cell to manage itself, then the delegate method (which will probably be implemented on your UITableViewController) can simply fetch the cell from the source table using its NSIndexPath (passed as a parameter to the delegate method) and invoke a method on the cell subclass to do its work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!