iPhone-alloc方法出现问题

为了SObject捕捉alloc:

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

在其他方法中执行都正常,只有在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

看起来你正在尝试使用method swizzling来自定义NSObject的alloc方法。


在调用method_exchangeImplementations函数时,你交换了allocCustom和alloc方法的实现。这意味着在你的代码中调用[NSObject alloc]时,实际上调用的是allocCustom方法。


但是,在allocCustom方法的实现中,你再次调用了[self allocCustom],这会导致递归调用,因此永远不会输出“no way”。


如果你希望在alloc方法被调用时执行一些自定义操作,你可以在allocCustom方法中实现它,然后使用[super alloc]来调用父类的alloc方法。例如:

(id)allocCustom {
    NSLog(@"%s", FUNCTION); // will be output
// Perform custom actions here
return [super alloc];
}