我的ISA-混写打破志愿(My isa-swizzling breaks KVO)

2019-06-25 19:16发布

我试图实现ISA混写,因为我需要一些动作某个对象的dealloc方法发生。 我重写 - (类)类; 方法返回原始类(如志愿一样)。 一切工作正常,直到我尝试观察者添加到绞合的对象。 它只是崩溃。

  1. 在00000000 00000000()
  2. 0x0091d22a在_NSKeyValueRetainedObservationInfoForObject()
  3. 0x0092ec88在 - [NSObject的(NSKeyValueObserverRegistration)_addObserver:forProperty:选择:上下文:]()
  4. 0x0092d6fd在 - [NSObject的(NSKeyValueObserverRegistration)的addObserver:forKeyPath:选择:上下文:]()

下面是实现混写的

- (void)swizzleClass
{
    NSString *proxyClassName = [NSString stringWithFormat:@"MDSwizzled_%@", NSStringFromClass(self->isa)];
    Class proxyClass = NSClassFromString(proxyClassName);

    if (!proxyClass)
        proxyClass = [self createProxyClassWithName:proxyClassName];

    object_setClass(self, proxyClass);
}

- (Class)createProxyClassWithName:(NSString *)proxyClassName
{
    const char *c_proxyClassName = [proxyClassName cStringUsingEncoding:NSUTF8StringEncoding];
    Class proxyClass = objc_allocateClassPair(self->isa, c_proxyClassName, 0);

    Class dummyClass = [MDDummy class];
    class_addMethodFromClass(proxyClass, dummyClass, @selector(dealloc));
    class_addMethodFromClass(proxyClass, dummyClass, @selector(class));

    objc_registerClassPair(proxyClass);
    return proxyClass;
}

MDDummy它只是一个在convinietn方式类保持的方法(也就是这一点,并添加原料的功能没有区别)。

@implementation MDDummy
- (void)dealloc
{

    //Special thinngs

    [super dealloc];
}

- (Class)class
{
    return //original class;
}
@end

编辑:

下面是实现class_addMethodFromClass功能:

void class_addMethodFromClass(Class class, Class sourceClass, SEL selector)
{
    Method method = class_getInstanceMethod(sourceClass, selector);
    IMP methodImplementation = method_getImplementation(method);
    const char *types = method_getTypeEncoding(method);
    class_addMethod(class, selector, methodImplementation, types);
}

Answer 1:

你应该看看迈克·阿什如何处理这样的: https://github.com/mikeash/MAZeroingWeakRef

总结:不同的处理混写一个志愿,搅和子类 - you'll需要修补的志愿子类的志愿方法...



文章来源: My isa-swizzling breaks KVO