I have a class object created dynamically using Runtime, and I want to release some manually allocated memory resources when this object is deallocated. To achieve this, I added a custom implementation of the dealloc method using the following code:
SEL aSel = NSSelectorFromString(@"dealloc");
class_addMethod(kvoClass, aSel, (IMP)custom_dealloc, method_getTypeEncoding(class_getInstanceMethod(kvoClass, aSel)));
However, I encountered some issues. If I don't call the superclass's dealloc method in the cus_dealloc function, the superclass's dealloc implementation will not be executed. On the other hand, if I explicitly call the superclass's dealloc method, the program crashes.
Here is the implementation of the cus_dealloc function:
void custom_dealloc(id self, SEL _cmd) {
// Release other memory

Class superClass = class_getSuperclass(object_getClass(self));
void (*originIMP)(struct objc_super *, SEL, ...) = (void *)objc_msgSendSuper;
struct objc_super *objcSuper = &(struct objc_super){self, superClass};
originIMP(objcSuper, _cmd);
}
I believe the issue here is that you’re using ARC. Specifically, in custom_dealloc
the call to objc_msgSendSuper
succeeds but then, after that, the code calls objc_storeStrong
to nil
out the reference it has to the object. However, the object has been deallocated and thus you die in objc_release
.
If you’re going to play the Silly Runtime Hacks™ game, you have to use MRR.
Taking a step back, what are you actually trying to do here?
It looks like you’re trying to reimplement KVO, and I strongly recommend against going down that path. KVO is super hard to implement correctly, to the point that I’m pretty sure that Apple’s implementation still has bugs in some corner cases.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"