本文介绍了SubstringWithRange NSString的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过X代码中的Leaks工具运行我的程序,它指出此功能是导致我的内存泄漏的主要原因.

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;
    }

特别是这一行

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

我不太确定要使用NSCFStrings和便捷方法进行内存管理,所以我有点困惑,有人可以给我一些指针吗?

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?

谢谢

推荐答案

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

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.

这篇关于SubstringWithRange NSString的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:08