ios - NSMutableDictionary 内存泄漏 - 如何在不崩溃应用程序的情况下修复它?

标签 ios iphone objective-c nsmutabledictionary

我一定误解了一些内存管理规则,因为当我尝试修复内存泄漏时,应用程序崩溃了。让我给你看一些代码:

calendarRequestLog 是单例对象中 MutableDictionary 类型的属性,只要应用程序运行,它就存在。这是 .h 文件中的声明:

@property (nonatomic, retain, readonly) NSMutableDictionary *calendarRequestLog;

我用(在初始化中)分配它:
calendarRequestLog = [[NSMutableDictionary alloc] init];

我用这个填充它(注意保留,这会造成内存泄漏):
[calendarRequestLog setObject:[[NSMutableArray arrayWithObject:delegate] retain] forKey:date];

我有时用这个来访问它:
NSMutableArray* delegates = [calendarRequestLog objectForKey:date];
if(delegates != nil) {
   // add delegates
}

我用这个清空它:
NSMutableArray* delegates = [calendarRequestLog objectForKey:date];    
if(delegates != nil) {
    for (id <ServerCallDelegate> delegate in delegates) { … }

    // clear the request from the log
    [calendarRequestLog removeObjectForKey:date];
}

这是我删除上面的保留时崩溃的代码:
NSMutableArray* delegates = [calendarRequestLog objectForKey:date];
if(delegates != nil) {
    if([delegates containsObject:delegate]) // crash
        [delegates removeObject:delegate];
}

它崩溃是因为委托(delegate)被释放但不是零。更准确地说,我得到一个 EXC_BAD_ACCESS 异常。

所有这些方法都可以以不同的顺序或多次调用。

我无法弄清楚,为什么会发生这种情况。我想,集合应该保留它们的对象——因为这个数组对象(委托(delegate))仍然在集合中,它不应该被释放。其他代码不负责任,我向您展示了所有出现的 calendarRequestLog。

我很感激我能得到的所有帮助!

@编辑
我想我明白了。

当委托(delegate)被解除分配时,我调用 crashing 方法,这样我以后就不会在每次事故中调用委托(delegate)。

但是:我在我的 calendarRequestLog 中保留了代表,所以只要不调用它就不能释放它:
    // clear the request from the log
    [calendarRequestLog removeObjectForKey:date];

...这反过来又会释放委托(delegate)并调用崩溃方法。由于 calendarRequestLog 已经删除了代表,但还不是关键,我们崩溃了。

好的,我会以不同的方式解决这个问题。感谢您的所有评论-感谢您,我在别处寻找!

最佳答案

您是否尝试在获取时保留,以便在您使用对象时没有人释放您的对象?

NSMutableArray* delegates = [[calendarRequestLog objectForKey:date] retain];
if(delegates != nil) {
     if([delegates containsObject:delegate]) // crash
          [delegates removeObject:delegate];
}
[delegates release];

关于ios - NSMutableDictionary 内存泄漏 - 如何在不崩溃应用程序的情况下修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6382610/

相关文章:

ios - 使用 Date UIPicker 和 Normal Picker 设置文本字段时出错,我尝试了很多东西但出现错误

ios - 检查字符串时间范围是否为现在

ios - Crashlytics 不显示崩溃报告

ios - 使用 UIGraphicsBeginImageContext 时内存泄漏

iphone - iOS键盘点击用户偏好

objective-c - cocoa 框架导入: is it necessary in headers if it's in your pch?

ios - Parse iOS Swift 快速入门指南后没有这样的模块 'Parse'

ios - CMPedometer 计步器不可用

ios - 将 UIImage 保存到应用程序路径中

iphone - 关于不使用 Interface Builder 进行 iPhone GUI 设计的教程?