Swizzling method for "alloc"?

I am trying to use the swizzling method to catch alloc for NSObject .

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

This is an implementation (category .m) that works in all other methods except alloc on NSObjet .

What could be the reason?

 #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.

+6
source share
1 answer

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

  • Use class_getClassMethod instead of class_getInstanceMethod
  • +allocCustom instead of -allocCustom
+8
source

Source: https://habr.com/ru/post/946077/


All Articles