【问题标题】:Memory leak with autoreleased strings iphone内存泄漏与自动释放的字符串 iphone
【发布时间】:2010-07-06 11:35:13
【问题描述】:

我正在尝试使用 Leak Instrument 清除我的应用程序的泄漏。 它显示了 xml 解析器 (TBXML) 的泄漏。

这是我将在解析时创建的一个类:

@interface GraphPoint : NSObject {
    NSString* x;
    NSString* y;
}


@property (nonatomic, copy) NSString* x;
@property (nonatomic, copy) NSString* y;

@end

@implementation GraphPoint

@synthesize x, y;

... some calculations

- (void) dealloc
{
    [x release];
    [y release];
    [super dealloc];
}

@end

在解析器中:

... // 当根据元素找到时:

        NSString    *str;
        GraphPoint  *aPoint = [[GraphPoint alloc] init];

        TBXMLElement *item = [TBXML childElementNamed:kX_Item parentElement:pntItem];
        str = [TBXML textForElement:item];  
        aPoint.x = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];     

        item = [TBXML childElementNamed:kY_Item parentElement:pntItem];
        str = [TBXML textForElement:item];  
        aPoint.y = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


        [points addObject:aPoint];
        [aPoint release];

Leaks instrument 在 TBXML 的 textForElement 函数中显示了泄漏,该函数提供了自动释放的字符串:

+ (NSString*) textForElement:(TBXMLElement*)aXMLElement {
    if (nil == aXMLElement->text) return @"";
    return [NSString stringWithCString:&aXMLElement->text[0] encoding:NSUTF8StringEncoding];
}

由于我们有时会谈论数百甚至数千个点,因此这些泄漏会变得很大。我不明白为什么自动释放的字符串会产生泄漏?

有什么想法吗?

谢谢

【问题讨论】:

    标签: cocoa-touch memory-leaks xml-parsing autorelease


    【解决方案1】:

    发布的代码中没有保留/释放问题。 textForElement: 中唯一的分配是 NSString 的 stringWithCString:encoding:,我怀疑它会泄漏。

    问题出在其他地方,无法用给定的信息来回答。您确定您正在正确读取仪器结果吗?静态分析对代码有何看法?

    我不了解 TBXML 库,但是包含 nil == aXMLElement->text 的行使它看起来有点可疑。这不是错误,而是样式问题:aXMLElement->text 似乎是 C 字符串,而 nil 用于 objc 对象。

    【讨论】:

    • 谢谢,你是对的,泄漏在其他地方 - 保存点数组的数组没有被释放
    猜你喜欢
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多