Memory Leak with SubstringWithRange NSString

2019-07-09 05:26发布

问题:

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\\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

回答1:

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.