使用stringByReplacingCharactersInRange问​​题保留/释放

时间:2010-12-18 19:53:22

标签: iphone objective-c memory-management

我正在观察仪器中的记忆足迹,并在我调用下面的方法时注意到一个巨大的峰值。该方法执行大量的字符串操作,我想知道我是否需要保留/释放NSStrings。如果有人想要改进这种方法,请告诉我。

-(void)findWords:(NSString *)query {
     //Removes Characters that aren't approved by me
     NSString *usersLetters = [query substringWithRange:allLetters];
     NSString *userLettersBackup = [query substringWithRange:allLetters];

     //Loop over all words in a NSDictionary
     for(NSString *word in wordSection)
     {
        int wordLength = [word length];

        //Loop Over each char in the word
        for (int i = 0; i < wordLength; i++)
        {
          char current = [word characterAtIndex:i];

           //Loop Over each char in the usersletters 
           for (int indexUser = 0; indexUser <[usersLetters length]; indexUser++)
           {
             char compare = [usersLetters characterAtIndex:indexUser];
             if(current == compare){
                //Is this losing reference to the other userLetters?
                //and retaining the previous value?
                usersLetters = [usersLetters stringByReplacingCharactersInRange:NSMakeRange(indexUser, 1) withString:@"*"];
             } 
           }
        }
        //Reset the UserLetters for looking at the next word
        usersLetters = userLettersBackup;
      }
 }

1 个答案:

答案 0 :(得分:3)

你的尖峰可能来自大量自动释放的对象。在内存管理方面,我没有看到任何直接错误。

您可以在方法开头alloc / init NSAutoreleasePool,最后drain