【发布时间】:2016-02-18 23:54:05
【问题描述】:
例如,让我们考虑 ARC 下的以下代码:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@implementation NSDate (MyEvilHack)
+ (void)load {
Method originalMethod = class_getInstanceMethod(self, @selector(copyWithZone:));
Method newMethod = class_getInstanceMethod(self, @selector(myCopyWithZone:));
method_exchangeImplementations(originalMethod, newMethod);
}
- (id)myCopyWithZone:(NSZone *)zone {
id result = [self myCopyWithZone:zone];
// do customization
return result;
}
@end
在这段代码中,原来的copyWithZone:方法是隐式返回一个保留对象,因为它属于copy方法族。但我的myCopyWithZone: 不是。
我预计会崩溃,但看起来这段代码工作正常。当然,我可以重命名我的方法以避免混淆。但我很好奇幕后到底发生了什么?
【问题讨论】:
标签: objective-c automatic-ref-counting method-swizzling