Xcode 中 NSString 的死存储和潜在泄漏
有点像一根绳子。使用以下代码(针对示例进行简化)时,我不断收到死存储和潜在泄漏的通知:
int x = 0;
NSString *aString = [NSString alloc]init]; <-- value store to 'aString' during its initialization is never read
if(x == 0)
{
aString = @"This is a string set by x being 0";
} else
{
aString = @"This is a string set by x being something else";
}
aTextLabelOutlet.text = aString;
[aString release];
<-- Potential leak of an object allocated online ... and stored into aString
我不太明白这一点。它被分配一次,然后在使用后释放。它被初始化,然后总是有一些东西被放入其中并且总是被读取。
它从未崩溃或实际上导致内存泄漏,所以我有点困惑。
Bit of a string one. I keep getting notified of a Dead Store and Potential Leak when using the following code (simplified for the example):
int x = 0;
NSString *aString = [NSString alloc]init]; <-- value store to 'aString' during its initialization is never read
if(x == 0)
{
aString = @"This is a string set by x being 0";
} else
{
aString = @"This is a string set by x being something else";
}
aTextLabelOutlet.text = aString;
[aString release];
<-- Potential leak of an object allocated online ... and stored into aString
I don't really understand this. It is alloc'ed once then released after use. It is initialised then always has something put into it and is always read.
It never crashed or actually causes a memory leak so I'm a bit confused.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该为
aString
分配NSString
,因为您在if
部分分配给aString
。这应该足够了:
You shouldn't allocate
NSString
foraString
, since you assign toaString
in theif
part.This should be enough:
问题是你已经分配了一个 NSString 但你没有释放它。您正在尝试释放使用
aString = @"..."
代码分配的字符串。由于对 aString 的第一次赋值从未被使用过,那么您不需要为 aString 提供另一个答案中提到的值(这也不会执行释放,因为字符串是静态分配的常量)
如果 String 确实有使用过的值您应该交换它们并释放它们。例如
,或者我会使用自动释放的字符串,这样运行时就会执行释放,
或者更好地使用构造函数类方法之一
The issue is that you have allocated a NSString but then you do not release it. You are trying to release the string you assigned with the
aString = @"..."
code.As the first assignment to aString is never used then you don't need to give aString a value as noted in the other answer (which also does not do a release as the strings are stsically allocated constants)
If a String did have a used value them you should swap over the assignment and release. e.g.
Or I woulduse an autoreleased string so hat the runtime will do the releasing i.e.
or better use one of the constructer class methods