2 lianlianbushell lianlianbushell 于 2013.06.09 13:22 提问

iPhone开发alloc方法混合使用

使用下面的方法为了捕捉通用NSObject中的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

1个回答

shuimoyichen
shuimoyichen   2018.01.11 10:00

使用下面的方法为了捕捉通用NSObject中的alloc。

NSObject *obj = [[NSObject alloc] init];
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
NSString *str = [[NSString alloc] init];
[...]
除了在NSObjet中的alloc,其他方法都能正常执行,为什么?

#import "NSObject+Custom.h"
#import

@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

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!