【问题标题】:Memory Leak with SubstringWithRange NSStringSubstringWithRange NSString 的内存泄漏
【发布时间】:2011-10-05 14:20:42
【问题描述】:

通过 X-Code 中的 Leaks 工具运行我的程序,它指出这个函数是我的内存泄漏的主要原因。

    + (NSMutableArray *) getColumns:(NSString *) deviceHtml {

        NSMutableArray *ret = [[[NSMutableArray alloc] init] autorelease];
        NSRegularExpression *m = [[NSRegularExpression alloc] initWithPattern:@"<td[\\w\\W\\d\\s</>]*?>[\\w\\W\\d\\s]+?</td>" options:NSRegularExpressionCaseInsensitive error:nil];

        NSArray *results = [m matchesInString:deviceHtml options:NSMatchingCompleted range:NSMakeRange(0, [deviceHtml length])];
        [m release];

        for (NSTextCheckingResult * res in results) {
            NSString *cleaned = [deviceHtml substringWithRange:[res range]];
            int firstClose = [cleaned rangeOfString:@">"].location;
            int cleanedLength = [cleaned length];
            NSString *cleaned1 = [cleaned substringWithRange:NSMakeRange(firstClose+1, cleanedLength-(firstClose+1))];
            int closingComment = [cleaned1 rangeOfString:@"</td"].location;
            NSString *cleaned2 = [cleaned1 substringWithRange:NSMakeRange(0, closingComment)];
            NSString *cleaned3 = [cleaned2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            [ret addObject:cleaned3];
        }
        return ret;
    }

特别是这一行,

    NSString *cleaned2 = [cleaned1 substringWithRange:NSMakeRange(0, closingComment)];

我不太确定使用 NSCFStrings 和便捷方法进行内存管理,所以我有点卡住了,谁能给我一些指点?

谢谢

【问题讨论】:

  • 我没有看到代码有任何明显错误。您确定该函数会导致内存泄漏(而不是分配峰值)吗?您是否尝试在 for 循环中使用本地 NSAutoreleasePool

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


【解决方案1】:

首先,方法不应该是getColumns:,而应该是columnsForDevice:get* 作为前缀在 Cocoa 中具有非常特殊的含义,这不是。

其次,泄漏工具会向您显示泄漏分配的位置,而不是可能实际发生泄漏的位置

如果返回的数组在其他地方被过度保留,那将是您的泄漏源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-26
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多