简体   繁体   English

目标C:单例中使用的字典内存泄漏

[英]Objective C: Memory Leak of Dictionary used in singleton

I am using a singleton class to share data between views in my iphone app. 我正在使用单例类在iPhone应用程序的视图之间共享数据。 My singleton class contains a dictionary which I allocate in my -init method: 我的单例类包含一个字典,该字典在我的-init方法中分配:

- (id)init
{        
   if ( self = [super init] )    
    {
            self.dataList = [[NSMutableDictionary alloc]init];

    }

    return self;
}

I release it in my dealloc method: 我用我的dealloc方法释放它:

- (void)dealloc
{   
    [dataList release];

    [super dealloc];
}

This dataList is downloaded from a server, and I do this multiple times in my app,so I have a custom setter method to release the old one, and retain the new one: 此dataList是从服务器下载的,我在我的应用中多次执行此操作,因此我有一个自定义的setter方法来释放旧的方法,并保留新的方法:

-(void) setDataList:(NSMutableDictionary*)d    
{
    if( dataList !=nil){

    [dataList release];
    dataList = [d retain];

else 
   dataList = [d retain];
}

ON using the leaks tool, I am getting a memory leak of the dictionary. 在使用泄漏工具时,我收到了字典的内存泄漏。 I think I am doing the alloc and release of the dictionary properly..does the leak occur because the dealloc method of the singleton is not getting called? 我想我正在正确地分配和释放字典..是否发生泄漏是因为未调用单例的dealloc方法?

Thanks for your help, 谢谢你的帮助,

Srikanth SRIKANTH

Add an autorelease: 添加自动发布:

self.dataList = [[[NSMutableDictionary alloc] init] autorelease];

When you assign a an object to a property it retains it and whenever you call and init method it retains, bringing the retain count to 2. 将对象分配给属性时,它将保留该对象,并且无论何时调用和init方法,都会保留该对象,从而使保留计数为2。

It also releases when you reassign it so you can just 重新分配时也会释放它,因此您可以

self.dataList = newValue;

@syntehsize'd properties take care of all the retain release stuff for you. @syntehsize的属性会为您处理所有保留发布的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM