【问题标题】:AsyncSocket and Notifications - memory leakAsyncSocket 和通知 - 内存泄漏
【发布时间】:2010-11-30 09:20:54
【问题描述】:

在以下情况下我有内存泄漏。我每 30 秒读取一次数据,使用 SBJSONParser 将其转换为字典,添加通知,然后使用数据将其绑定到 tableview:

// Read data and send notification
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *content = [[NSString alloc] initWithData:[data subDataWithRange:NSMakeRange(0, [data length] - 2)] encoding: NSUTF8StringEncoding];

    // Line where leaks appear
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]];

    [content release];

    // Post notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict];

     [dict release];
}

在 CustomViewController 我有观察者:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindData) name:@"BindData" object:nil];

和 bindData 方法:

-(void)bindData:(NSNotification*)notification
{
    NSAutoreleasePool* pool = [[NSAutoReleasePool alloc] init];

    NSMutableArray* customers = [notification.userInfo objectForKey:@"Customers"];
    for (NSDictionary* customer in customers)
    {
         Company* company = [[Company alloc] init];
         company.name = [customer objectForKey:@"CompanyName"];
         NSLog(@"Company name = %@", company.name);
         [company release];
    }

    [pool drain];
}

问题是:当我设置 company.name = 该字典中的某些内容时,我在线上出现内存泄漏: NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:[content JSONValue]];因为我每 30 秒阅读一次,所以它一直在增加。

感谢您提供的任何帮助。谢谢。

【问题讨论】:

    标签: iphone objective-c asyncsocket


    【解决方案1】:

    dict 正在泄漏,因为您正在使用 allocinit(因此将其保留计数增加 1),但从未释放它。由于发布通知后将不再需要字典,因此您可以在以下行安全地释放它,如下所示:

    // Post notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict]
    [dict release];
    

    有关详细信息,请参阅Memory Management Programming Guide

    【讨论】:

    • 感谢您的评论。我确实在我的代码中释放了字典,我只是忘记在初始消息中添加它,我只是编辑它,所以即使我释放字典,问题仍然存在。
    • 如果是这样,那么您发布的代码就没有泄漏。它可能在上面未包含的某些部分中。
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 2010-12-02
    • 2013-11-08
    • 2016-05-03
    • 2011-11-25
    • 2010-11-19
    • 2014-09-27
    • 2013-07-31
    相关资源
    最近更新 更多