如果在没有子类化和重写dealloc方法的情况下取消分配对象,如何在类类别中触发操作。我正在尝试在UIView
上实施一个类别。
答案 0 :(得分:1)
swizzle dealloc。它是邪恶的,但我们也这样做:D
在你的类别的加载中,你可以使用
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface T : NSObject
@end
@interface T (myCat)
@end
@implementation T
- (void)dealloc {
NSLog(@"2");
}
@end
@implementation T (myCat)
+ (void)load {
SEL originalSelector = @selector(NSSelectorFromString(dealloc));
SEL overrideSelector = @selector(xchg_dealloc);
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method overrideMethod = class_getInstanceMethod(self, overrideSelector);
if (class_addMethod(self, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(self, overrideSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, overrideMethod);
}
}
- (void)xchg_dealloc {
NSLog(@"1");
[self xchg_dealloc]; //calls original
}
@end
答案 1 :(得分:1)
如果你不喜欢调酒,可能会有更少的邪恶但更脆弱的东西。令人费解的方式
您使用的Helper对象会被运行时解除分配为某种标记
@interface T_Helper : NSObject
@public
__weak T *parent;
@end
@implementation T_Helper
- (void)dealloc {
[parent my_dealloc];
}
@end
@implementation T (myCat)
- (void)doSomethingThatLaterWantsDealloc {
T_Helper *helper = [T_Helper alloc] init];
helper->parent = self;
objc_setAssociatedObject(self, "helper", helper, OBJ_ASSOSIATION_RETAIN);
}
- (void)my_dealloc {
NSLog(@"1");
}
@end