Is there any way to call a method before deallocating any NSObject Class object.
or
Is it possible to writing custom dealloc method for NSObject Class so that
we can call any method before deallocating that object?
As garbage collector is not available for iPhone, I wants to create small framework which handles memory leak at runtime & create a log files for leaks (I known that there is instrument that identify the leaks but still for R&D and don't want to implement Garbage Collector algo).
We are trying to maintain a list of allocated object.
for example:
A *a=[[A alloc]init];
NSString * veribaleAddress=[NSString stringWithFormat:@"%p",&a];
NSString *allocatedMemoryAddress=[NSString stringWithFormat:@"%p",a];
// Global dictionary for maintaining a list of object NSMutableDictionary *objects;
[objects setValue: allocatedMemoryAddress forKey: veribaleAddress];
but when any object get deallocate then I want to 1st look, whether address of that object is present in dictionary or not. If address present then remove it from dictionary.
Please guide me, whether it's possible or not.
Thanks
Here’s an example gist showing how to swizzle the dealloc
method, if that’s what you are after. Main part of the code:
void swizzle(Class c, SEL orig, SEL patch)
{
Method origMethod = class_getInstanceMethod(c, orig);
Method patchMethod = class_getInstanceMethod(c, patch);
BOOL added = class_addMethod(c, orig,
method_getImplementation(patchMethod),
method_getTypeEncoding(patchMethod));
if (added) {
class_replaceMethod(c, patch,
method_getImplementation(origMethod),
method_getTypeEncoding(origMethod));
return;
}
method_exchangeImplementations(origMethod, patchMethod);
}
id swizzledDealloc(id self, SEL _cmd)
{
// …whatever…
return self;
}
const SEL deallocSel = @selector(dealloc);
// If using ARC, try:
// const SEL deallocSel = NSSelectorFromString(@"dealloc");
const SEL swizzledSel = @selector(swizzledDealloc);
class_addMethod(c, swizzledSel, (IMP) swizzledDealloc, "@@:");
swizzle(c, deallocSel, swizzledSel);
As Bavarious says, this is dark magic and I wouldn’t use it in production, ever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With