1

i have an unexpected behavior while swizzling a method on a UITableViewCell category

my .m file :

#import "UICollectionViewCell+CostraintFix.h"
#import <objc/runtime.h>

@implementation UICollectionViewCell (CostraintFix)

+(void)load {
    Method original_setBounds, swizzled_setBounds;
    original_setBounds = class_getInstanceMethod(self, @selector(setBounds:));
    swizzled_setBounds = class_getInstanceMethod(self, @selector(swizzled_setBounds:));

    method_exchangeImplementations(original_setBounds, swizzled_setBounds);

}

- (void) swizzled_setBounds:(CGRect) bounds{
    [self swizzled_setBounds:bounds];
    self.contentView.frame = bounds;
}
@end

Well, when i start my project i have this:

-[UINavigationButton swizzled_setBounds:]: unrecognized selector sent to instance 0x7fe2dbb301c0
  1. This is 100% a UICollectionViewCell category.
  2. At this point, in +(void) load, only UITableViewCell class are passing (as expected)
Rahul Mane
  • 1,005
  • 18
  • 33
Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40
  • This is strange indeed... Based on what you posted, everything seems OK, including the inheritance call, which a lot of people get wrong when dealing with method swizzling. Where in your project are you using `UINavigationButton`? How is your `UICollectionViewCell` getting initialized? Also, try to follow this pattern from NSHipster, which is a little bit more complicated than what you did (notably, they recommend always doing this in a `dispatch_once` - never hurts to try), and see if it works better? http://nshipster.com/method-swizzling/ – Romain Feb 08 '15 at 12:57
  • That's the funny thing: i don't use directly UINavigationButtons... it is a private class (the backbutton for example) the sizes of this UINavigationButton suggest me that is my left bar button item of the UIViewController containing the collectionView. The strangest thig of all this story, is that inside the load method, only UICollectionViewCell are interested... i really have no idea how this is possible. I import this category in my appDelegate. – Giuseppe Lanza Feb 08 '15 at 15:40
  • Set a breakpoint in your `+ (void)load` method and see if it gets called multiple times during runtime? – Romain Feb 08 '15 at 15:42
  • Done. only once, then it crashes – Giuseppe Lanza Feb 08 '15 at 15:51
  • @GiuseppeLanza, can you provide more information. So the question is about replacing method in UICollectionView category seems, but there is a crash in some other item also there is an UITableViewCell. Also here is an static method +load. – Matrosov Oleksandr Feb 09 '15 at 11:31

1 Answers1

1

Found the problem. If you swizzle a method of a subclass which does not overrides the method, then you will override its super class method. its superclass could not respond to some selectors; of course this is the case.

Thank you for the help by the way

Giuseppe Lanza
  • 3,519
  • 1
  • 18
  • 40