我尝试使用方法调整来捕获 NSObject 泛型的“ alloc ”。
NSObject *obj = [[NSObject alloc] init];
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
NSString *str = [[NSString alloc] init];
[...]
这是实现(类别.m),适用于所有其他方法,除了NSObjet上的alloc 。
可能是什么原因?
#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
感谢。
答案 0 :(得分:8)
+alloc
是一个类方法,而不是实例方法:
class_getClassMethod
代替class_getInstanceMethod
+allocCustom
代替-allocCustom