0

一直在玩弄工具,但在弄清楚如何解决此内存泄漏方面运气不佳。

首先是代码:

-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSMutableString * outputstring = [NSMutableString stringWithCapacity:[wordToShuffle length]];
    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];
        }

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];
        [outputstring appendFormat:@"%c",[wordToShuffle characterAtIndex:randomnum]];
    }

    CCLOG(@"outputstring is:%@",outputstring);
    return outputstring;

 }

Instruments 给了我以下信息:

Leaked Object = NSCFString, Responsible Library = Foundation, Responsible Frame = -[NSPlaceholderMutableString initWithCapacity:]

有任何想法吗?

提前致谢。

4

2 回答 2

2

你真的不需要使用可变字符串......特别是因为你的返回类型是 NSString。只需使用 stringByAppendingFormat:

-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSString * outputstring = @"";

    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];
        }

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];

        // just set outputstring like so... no need to worry about a leaky mutable string then
        outputstring = [outputstring stringByAppendingFormat:@"%c",
                    [wordToShuffle characterAtIndex:randomnum]];
    }


    return outputstring;

}
于 2012-07-16T16:53:46.383 回答
0

查看返回的字符串在哪里使用。可能您正在保留它并解除分配保留字符串的对象,而无需先释放保留的字符串。Instruments 仍会将这部分代码指向“泄露”的对象。最难的部分是找到“泄密者”。是的,你可以泄露一个字符串,我刚刚写了它的配方。

于 2012-07-16T17:00:06.823 回答