2011-07-14 31 views
2

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

+ (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和方便的方法,内存管理,所以我有点卡住,任何人都可以给我一些指点?

感谢

+3

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

回答

2

首先,该方法不应该是getColumns:但是,比如说,像columnsForDevice:get*作为前缀在Cocoa中有非常具体的含义,这不是它。

其次,泄漏的仪器显示你在哪里一个泄密被分配,不泄漏位置实际上可能发生

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