繁体   English   中英

iPhone:自定义类和NSMutableDictionary中的内存泄漏

[英]iPhone: Memory Leak in Custom Class and NSMutableDictionary

我花了几天的时间试图找出正在发生的事情。 我已经阅读了很多内存管理文档,并且听到“为您需要释放的每个分配”而感到厌烦-我知道,而且我仍然无法弄清楚为什么我的代码会产生内存泄漏。

我正在编写一个简单的自定义类,将NSMutableDictionary作为其属性之一。 基本上,它模仿XMLELement。 我一生都无法弄清为什么分配字典会导致内存泄漏。 设备和模拟器上均发生泄漏-设备上发生5次泄漏,模拟器上发生20次泄漏。

当我声明并分配变量* tmp时,就会发生泄漏。
设置属性详细信息(名称和值)时也会泄漏。

这让我发疯。 请帮忙!

部分代码:

 @interface IMXMLElement : NSObject { NSString *strElementName; NSString *strElementValue; NSMutableDictionary *dictAttributes; } @property (nonatomic, retain) NSString *strElementName; @property (nonatomic, retain) NSString *strElementValue; @property (nonatomic, retain) NSMutableDictionary *dictAttributes; @end @implementation IMXMLElement @synthesize strElementName; @synthesize strElementValue; @synthesize dictAttributes; -(id)initWithName:(NSString *)pstrName { self = [super init]; if (self != nil) { self.strElementName = pstrName; **LEAK NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init]; self.dictAttributes = tmp; [tmp release]; } return self; } -(void)setAttributeWithName:(NSString *)pstrAttributeName andValue:(NSString *)pstrAttributeValue { **LEAK [self.dictAttributes setObject:pstrAttributeValue forKey:pstrAttributeName]; } -(void)dealloc { [strElementName release]; [strElementValue release]; [dictAttributes release]; [super dealloc]; } 

使用以下代码访问此类:

NSString *strValue = [[NSString alloc] initWithFormat:@"Test Value"];

 IMXMLElement *xmlElement = [[IMXMLElement alloc] initWithName:@"Test_Element"]; [xmlElement setAttributeWithName:@"id" andValue:strValue]; 

释放dictAttributes之前,请尝试[dictAttributes removeAllObjects]。

编辑:

另外,您将肯定分配,因为您正在为“ tmp”分配内存。 内存将被保留,因为您现在有了dictAttributes的引用。

然后,当您向字典中添加元素时,您将获得更多的正分配,这些元素也需要分配,并由字典的内部引用保存在内存中

典型语法为NSMutableDictionary *tmp = [[[NSMutableDictionary alloc] init] autorelease];

将字符串作为属性时,将其声明为副本,而不保留。

  NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init];
  self.dictAttributes = tmp;
  [tmp release];

上面的步骤是不必要的,而是执行以下操作:( 此自动释放对象的保留计数将自动增加)

self.dictAttributes = [NSMutableDictionary dictionaryWithCapacity:0];

在dealloc中执行:( 保留计数将自动减少)

self.dictAttributes = nil;

通常对于属性,您只需将它们设置为nil即可,而不是显式释放它们,因为get / setter会为您处理。

暂无
暂无

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

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