Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method swizzling for "alloc"?

I try to use method swizzling for catching "alloc" for NSObject generic.

NSObject *obj = [[NSObject alloc] init];
UIView *view  = [[UIView alloc] initWithFrame:CGRectZero];
NSString *str = [[NSString alloc] init];
[...]

This is the implementation (category .m), that works on all others methods, except alloc on NSObjet.

What could be the cause?

#import "NSObject+Custom.h"
#import <objc/runtime.h>

@implementation NSObject (Custom)

+ (void)load
{
  Method original = class_getInstanceMethod(self, @selector(alloc));
  Method swizzle  = class_getInstanceMethod(self, @selector(allocCustom));
  method_exchangeImplementations(original, swizzle);
}

- (id)allocCustom
{
  NSLog(@"%s", __FUNCTION__); // no way
  return [self allocCustom];
}

@end

thanks.

like image 715
elp Avatar asked May 29 '13 10:05

elp


1 Answers

+alloc is a class method, not an instance method:

  • Use class_getClassMethod instead of class_getInstanceMethod
  • +allocCustom instead of -allocCustom
like image 74
一二三 Avatar answered Oct 02 '22 12:10

一二三