I am trying to inject my code at runtime to delegate tableView: didSelectRowAtIndexPath :. I have the following code:
static void overridingDidSelectCellAtIndexPath(void (^listener)(id _self, UITableView *tableView, NSIndexPath *indexPath)) {
Method didSelectRowAtIndexPath = class_getInstanceMethod([ViewController class], @selector(tableView:didSelectRowAtIndexPath:));
IMP originalImp = method_getImplementation(didSelectRowAtIndexPath);
void (^bl)(id, UITableView *, NSIndexPath *) = ^(id _self, UITableView *tableView, NSIndexPath *indexPath) {
originalImp(_self, @selector(tableView:didSelectRowAtIndexPath:), tableView, indexPath);
listener(_self, tableView, indexPath);
};
IMP newImp = imp_implementationWithBlock((__bridge id)((__bridge void*)bl));
method_setImplementation(didSelectRowAtIndexPath, newImp);
}
I call it in:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
overridingDidSelectCellAtIndexPath(^(id _self, UITableView *tableView, NSIndexPath *indexPath) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell.textLabel setText:@"Hello"];
});
return [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}
The line that causes the failure:
originalImp(_self, @selector(tableView:didSelectRowAtIndexPath:), tableView, indexPath);
I get no exception, my backtrace from lldb:
* thread
'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x8)
frame
frame
GetAllMethods`__overridingDidSelectCellAtIndexPath_block_invoke(.block_descriptor=0x14d49870, _self=0x14d48690, tableView=0x15121400, indexPath=0x14d51870) + 120 at ViewController.m:68
frame
frame
frame
frame
frame
frame
frame
frame
frame
frame
frame
frame