gpt4 book ai didi

iphone - 取消分配任何对象之前的回调方法

转载 作者:太空狗 更新时间:2023-10-30 03:36:19 25 4
gpt4 key购买 nike

在释放任何 NSObject 类对象之前,有没有办法调用方法。

是否可以为 NSObject 类编写自定义 dealloc 方法以便
我们可以在释放该对象之前调用任何方法吗?

由于垃圾收集器不适用于 iPhone,我想创建一个小型框架来处理运行时的内存泄漏并为泄漏创建一个日志文件(我知道有一种工具可以识别泄漏,但仍然用于研发,但不想要实现垃圾收集器算法)。

我们正试图维护一个已分配对象的列表。

例如:

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];

但是当任何对象被释放时,我想首先看一下,该对象的地址是否存在于字典中。如果存在地址,则将其从字典中删除。

请指导我,无论是否可行。

谢谢

最佳答案

这是一个 example gist显示如何 swizzle dealloc 方法,如果这就是您所追求的。代码主要部分:

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);

正如 Bavarious 所说,这是黑魔法,我永远不会在生产中使用它。

关于iphone - 取消分配任何对象之前的回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5960049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com