1

I am using method swizzling in my project using (JRSwizzle). I have implemented swizzling for "UIViewController" and "UIButton". It works fine.

But i am having trouble in swizzling a UITableViewDelegate method "willDisplayCell". Can anyone provide me a working sample of this?

As i understand,

Step 1: We need to create a category of the class we want to swizzle.

Example: UIViewController+Swizzle or UIButton+Swizzle

Step 2: Implement the +load and swizzleMethod like below

 + (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSError *error;
        BOOL result = [[self class] jr_swizzleMethod:@selector(viewWillAppear:) withMethod:@selector(xxx_viewWillAppear) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }
    });
}

- (void)xxx_viewWillAppear
{
    [self xxx_viewWillAppear]; // this will call viewWillAppear implementation, because we have exchanged them.
    //TODO: add customer code here. This code will work for every ViewController
    NSLog(@"xxx_viewWillAppear for - %@", NSStringFromClass(self.class));
}

But, if i create a category for "UITableViewController" and do the method swizzle like below,

   + (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSError *error;
        BOOL result = [[self class] jr_swizzleMethod:@selector(willDisplayCell:) withMethod:@selector(xxx_willDisplayCell) error:&error];
        if (!result || error) {
            NSLog(@"Can't swizzle methods - %@", [error description]);
        }
    });
}

- (void)xxx_willDisplayCell
{

}

The BOOL result is always "NO" and says something like "method not found or available". That may be because "willDisplayCell" is a delegate method of "UITableViewDelegate" and not "UITableViewController"

That being the case, i cannot do step 1 above. That is, i cannot create a category for "UITableViewDelegate". XCode doesn't even allow that.

And this is were i am stuck. Completely clueless on how to do this. Can someone help here!!

MaK
  • 81
  • 1
  • 7
  • The method is `tableView:willDisplayCell:forRowAtIndexPath:`, but why are you using swizzling instead of inheritance? – jscs Sep 29 '16 at 19:04
  • Thank you Josh! It's an already existing project and there are already many tableviewcontrollers used. I thought it would be safe not touch exisitng code. I tried this solution, i mean the method you provided but i am not sure the category file which i create should be of "UITableViewController" or "UITablewViewDelegate"? WIth first approach its says "No method found" and second approach as i said is not even allowing to create category of UITablewVIewDelegate – MaK Sep 29 '16 at 19:15

0 Answers0