首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsyncSocket和通知-内存泄漏

AsyncSocket和通知-内存泄漏
EN

Stack Overflow用户
提问于 2010-11-30 17:20:55
回答 1查看 629关注 0票数 0

在下面的场景中,我遇到了内存泄漏。我每隔30秒读取一次数据,使用SBJSONParser将其转换为字典,添加通知,然后使用数据将其绑定到表视图:

代码语言:javascript
复制
// 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上,我有观察者:

代码语言:javascript
复制
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bindData) name:@"BindData" object:nil];

和bindData方法:

代码语言:javascript
复制
-(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 = something时,我得到了一行内存泄漏: NSMutableDictionary* dict = [NSMutableDictionary alloc initWithDictionary:content JSONValue];由于我每隔30秒阅读一次,它一直在增加。

我感谢你能给我的任何帮助。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2010-11-30 17:36:31

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

代码语言:javascript
复制
// Post notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"BindData" object:nil userInfo:dict]
[dict release];

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4312128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档