UIView + Category访问dealloc或在UIView dealloc调用上执行某些操作

时间:2014-01-23 11:33:31

标签: ios iphone uikit

如果在没有子类化和重写dealloc方法的情况下取消分配对象,如何在类类别中触发操作。我正在尝试在UIView上实施一个类别。

2 个答案:

答案 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