Libor Zapletal
Libor Zapletal

Reputation: 14102

iOS handle didSelectRowAtIndexPath in custom class

I've seen a way how to set handler for events in custom classes. Something like this:

@implementation CustomClassWithTable {
    void (^_cellHandler)(Cell *cell);
}

...

- (void)setCellHandler:(void (^)(Cell *))handler
{
    _cellHandler = handler;
}

...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ... 
    if (_cellHandler) {
        _cellHandler(cell);
    }
}

then in controller it just need to set cellHandler and it works. I like it. First of all what is name of this aproach (pattern)? Second how can I do this in swift? And is it the best aproach? Lets say I have table in my custom class (menu) and I want to be able get selected cell in my view controller. Should I use this aproach or something else (delegate pattern for example)?

Upvotes: 2

Views: 203

Answers (1)

Fergal Rooney
Fergal Rooney

Reputation: 1390

What you are doing in the above code is delegation by using an objective C block. Swift has a similar feature called a closure. Because this block has the ability to bet set at runtime, you could also be using the strategy pattern to delegate different behavior when a table row is selected.

var cellHandler : ((cell: Cell) -> Void)?

if let callback = cellHandler {
    callback(cell)
}

Upvotes: 1

Related Questions