泄漏在哪里?

时间:2012-04-26 08:42:23

标签: iphone objective-c ios memory-management memory-leaks

if ([elementName isEqualToString:@"type"])
    {
        items       = [[NSMutableDictionary alloc] init];
        currentname = [[NSMutableString alloc] init];
        currentid   = [[NSMutableString alloc] init];
    }

resolv如何泄漏问题

3 个答案:

答案 0 :(得分:2)

currentElement = [elementName copy];
items          = [[NSMutableDictionary alloc] init];
currentname    = [[NSMutableString alloc] init];
currentid      = [[NSMutableString alloc] init];

您泄漏了存储在这些ivars中的先前值。

答案 1 :(得分:1)

  • currentElement = [elementName copy];
  • items = [[NSMutableDictionary alloc] init];
  • currentname = [[NSMutableString alloc] init];
  • currentid = [[NSMutableString alloc] init];

如果方法parser:didStartElement:namespaceURI:qualifiedName:attributes:运行多次,这些都会导致内存泄漏。

解决此问题的一种简单方法是将变量更改为属性。例如,在头文件中,更改:

@interface SomeClass {
    NSMutableDictionary *items;
}

为:

@interface SomeClass {
}

@property (retain) NSMutableDictionary *items;

@implementation SomeClass之后添加:

@synthesize items;

然后将原始代码更改为:

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

当你想检查内存问题时,Xcode和Instruments中的“Analyze”功能都是你的朋友。

答案 2 :(得分:0)

如果您确定此代码段中存在泄漏,我假设您已经运行了Instruments,它告诉您NSString对象“elementName”正在泄漏。

Romain是对的:一个很好的步骤是运行Xcode静态分析器。它可能会告诉您[elementName copy]返回保留计数为+1的对象。 (根据Cocoa约定,所有“复制”选择器都将返回对象的所有权转移到您的代码中。)

因此,这里的解决方案是通过在不需要时释放复制的对象来平衡“复制”调用,使用:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{ 
     [currentElement release];
     currentElement = [elementName copy];

     // your method body here…
 }
相关问题