开发者

Memory Leak with SubstringWithRange NSString

Running my program through the Leaks tool in X-Code, it points to this function as the main cause of my memory leaks.

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

        NSMutableArray *ret = [[[NSMutableArray alloc] init] autorelease];
        NSRegularExpression *m = [[NSRegularExpression alloc] initWithPattern:@"<td[\\w\\W\\d\\s</>]*?>[\\w\\W\\开发者_Go百科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;
    }

Specifically this line,

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

I'm not really sure about memory management with NSCFStrings and convenience methods so I'm a little stuck, can anyone give me a few pointers?

Thanks


First, the method should not be getColumns: but, say, something like columnsForDevice:. get* as a prefix has a very specific meaning in Cocoa and this isn't it.

Secondly, the Leaks instrument shows you where a leak was allocated, not where the leak may actually be happening.

If the returned array is over-retained elsewhere, that would be the source of your leak.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜