I have this method:
我有这个方法:
-(NSString *)scrambleWordGenerator: (NSUInteger)length {
NSMutableString *scrambledWord = [[NSMutableString alloc] initWithString:@""];
for (int i = 0; i < length; i++) {
NSUInteger randomIndex = arc4random() % [self.arrayOfCharacters count];
NSString *randomCharacter = [NSString stringWithString:[self.arrayOfCharacters objectAtIndex:randomIndex]];
[scrambledWord insertString:randomCharacter atIndex:i];
}
NSString *finalWord = [[NSString alloc] initWithString:scrambledWord];
[scrambledWord release];
return finalWord;
}
It works, swimmingly in fact, however upon using Xcode's "Analysis" feature, it says that finalWord
has a potential memory leak.
事实上它可以游泳,但是在使用Xcode的“分析”功能时,它表示finalWord有潜在的内存泄漏。
I thought when creating a NSString
with a prefab init
method that the string will be autoreleased. What am I missing? Below is a screen grab of the error:
我想在使用预制init方法创建一个NSString时,该字符串将被自动释放。我错过了什么?下面是错误的屏幕抓取:
edit
编辑
The method now looks like this:
该方法现在看起来像这样:
-(NSString *)scrambleWordGenerator: (NSUInteger)length {
NSMutableString *scrambledWord = [[NSMutableString alloc] initWithString:@""];
for (int i = 0; i < length; i++) {
NSUInteger randomIndex = arc4random() % [self.arrayOfCharacters count];
NSString *randomCharacter = [NSString stringWithString:[self.arrayOfCharacters objectAtIndex:randomIndex]];
[scrambledWord insertString:randomCharacter atIndex:i];
}
NSString *finalWord = [NSString stringWithString:scrambledWord];
[scrambledWord release];
return finalWord;
}
And no more errors!
没有更多的错误!
1 个解决方案
#1
3
No, the moment you use alloc
, you're responsible for releasing it - either by release
or by moving it to autorelease pool via autorelease
.
不,在您使用alloc的那一刻,您负责释放它 - 通过发布或通过自动释放将其移动到自动释放池。
It would be on the autorelease pool if you used [NSString stringWithString:]
instead.
如果您使用[NSString stringWithString:],它将在自动释放池中。
#1
3
No, the moment you use alloc
, you're responsible for releasing it - either by release
or by moving it to autorelease pool via autorelease
.
不,在您使用alloc的那一刻,您负责释放它 - 通过发布或通过自动释放将其移动到自动释放池。
It would be on the autorelease pool if you used [NSString stringWithString:]
instead.
如果您使用[NSString stringWithString:],它将在自动释放池中。