一直在玩弄没有太多运气的乐器,以找出如何解决这种内存泄漏问题。
首先是代码:
-(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;
}
仪器给了我以下内容:
Leaked Object = NSCFString, Responsible Library = Foundation, Responsible Frame = -[NSPlaceholderMutableString initWithCapacity:]
有什么想法吗?
提前致谢。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
查看返回字符串的使用位置。可能你保留它并释放保留字符串的对象而不首先释放保留的字符串。仪器仍将指向此部分代码作为“泄露”对象。最困难的部分是找到'泄漏者'。是的,你可以泄漏一个字符串,我只是为它写了食谱。