The problem is this:
I need to be able to get analytics on didSelectRowAtIndexPath throughout a big existing app with lots of tableViews.
My first thought of this is doing method swizzling on didSelectRowAtIndexPath: but my app crashes with "unrecognized selector sent to instance" message depending on the stuff is accessed in the original didSelectRowAtIndexPath implementation.
Here is how I try to achieve this in a UIViewController category:
#import "UIViewController+Swizzle.h"
@implementation UIViewController (Swizzle)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPathSwizzled:(NSIndexPath *)indexPath {
NSLog(@"Log something here");
[self tableView:tableView didSelectRowAtIndexPathSwizzled:indexPath];
}
+ (void) initialize {
BOOL conformsToTableViewDelegate = class_conformsToProtocol(self, @protocol(UITableViewDelegate));
if(conformsToTableViewDelegate) {
Method method1 = class_getInstanceMethod(self, @selector(tableView:didSelectRowAtIndexPath:));
Method method2 = class_getInstanceMethod(self, @selector(tableView:didSelectRowAtIndexPathSwizzled:));
method_exchangeImplementations(method1, method2);
}
}
@end
Can this be accomplished? If so, what am I doing wrong?
Thanks!
+initialize
like this will override the+initialize
inUIViewController
, if any. And this code will result in every single instance ofUIViewController
or subclass to have that method swizzled. This has nothing to do with "methods in protocols" and everything to do with changing the internal behavior of the UIKit. – Dolt+initialize
in a category; you'll be overridingUIViewController
's+initialize
(if it has one now or at any time in the future). Modifying system provided classes is verboten for a reason; it causes mysterious behaviors and crashes, even when you think what you are doing is harmless. Post the crash. – Dolt