Memory Leak with SubstringWithRange NSString

血红的双手。 提交于 2019-12-24 02:18:13

问题


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.



来源:https://stackoverflow.com/questions/6698046/memory-leak-with-substringwithrange-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!