My KVO night breaks

I try to implement isa swizzling because I need to perform some actions in the dealloc method of a specific object. I overestimate class (class); method to return the source class (as KVO does). Everything works fine until I try to add an observer to the swizzled object. He just falls.

  • 0x00000000 to 0x00000000 ()
  • 0x0091d22a in _NSKeyValueRetainedObservationInfoForObject ()
  • 0x0092ec88 in - [NSObject (NSKeyValueObserverRegistration) _addObserver: forProperty: options: context:] ()
  • 0x0092d6fd in - [NSObject (NSKeyValueObserverRegistration) addObserver: forKeyPath: options: context:] ()

Here is the swizzling implementation

- (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 is just a convietn method of holding a class (there is no difference between this and adding raw functions).

 @implementation MDDummy - (void)dealloc { //Special thinngs [super dealloc]; } - (Class)class { return //original class; } @end 

EDIT:

Here's the implementation of the class_addMethodFromClass function:

 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); } 
+5
objective-c objective-c-runtime key-value-observing swizzling
source share
1 answer

You should check how Mike Ash handles this: https://github.com/mikeash/MAZeroingWeakRef

Summary: Handling the KVO-swizzled subclass in different ways - you will have to fix the KVO methods in the KVO subclass ...

+3
source share

All Articles