Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - How to implement custom callback method but enforce specific parameter?

In my app I have a custom UITableViewCell subclass that pops up a picker when pressed. from now on I'll refer to this class as PickerCell. I'm using several of instances of PickerCell in the same UITableView.

I don't want the cell to respond to the selection of a row in the picker, because it's not a good MVC. Instead I want the ViewController to give the cell a callback that will be called upon selection of row.

The most obvious way is to create a protocol like PickerCellDelegate and the view controller will pass himself to each cell.

My problem with this approach is that since I have several PickerCells, my implementation of the protocol in the ViewController will have to distinguish between each cell:

-(void) pickerCell : (PickerCell *) sender 
      didSelectRow : (NSInteger) row 
       inComponent : (NSInteger) component
{
    if (sender == X)
    // Something
    else if (sender == Y)
    // Something else...
    // etc...
}

And I hate this coding style...

Instead I would really like a mechanism that allow the ViewController to give it's own callback.

I can allow the PickerCell to accept a "onRowSelectedSelector", but then how do I ensure that this selector is in the format that I want? (Number of parameters is the most important)

Even better, I would like to give the Picker cell a block to execute on selection, because I know blocks can be defined with specific parameters. In addition there is no need to pass a "target" object.

So how do I do such a thing?

Thanks!

like image 878
Avi Shukron Avatar asked Mar 28 '12 08:03

Avi Shukron


1 Answers

this is how to use block callback

typedef void(^PickerCallback)(NSInteger row, NSInteger component);

@interface PickerCell 

@property (nonatomic, copy) PickerCallback callback;

@end

@implementation PickerCell

@synthesize callback;

- (void)whatever {
    // when you want to call the callback block
    if (self.callback) {
        self.callback(row, component);
    }
}

@end

and assign callback block after picker cell created

PickerCell *cell = // create a picker cell
cell.callback = ^(NSInteger row, NSInteger component) {
    // inside callback
};
like image 91
Bryan Chen Avatar answered Sep 19 '22 01:09

Bryan Chen