字符串之一。使用以下代码时,我会不断收到Dead Store和潜在泄漏的通知(示例简化):
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
我真的不明白这一点。它被分配一次然后在使用后释放。它被初始化然后总是放入其中并且总是被读取。
它从未崩溃或实际上导致内存泄漏,所以我有点困惑。
答案 0 :(得分:6)
您不应为NSString
分配aString
,因为您已在aString
部分分配给if
。
这应该足够了:
int x = 0;
NSString *aString;
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;
答案 1 :(得分:0)
问题是你已经分配了一个NSString,但是你没有释放它。您正尝试使用aString = @"..."
代码释放您指定的字符串。
由于从未使用过aString的第一个赋值,所以你不需要给aString一个值,如另一个答案中所述(由于字符串是明确分配的常量,它也不会发布)
如果String确实具有使用值,则应交换赋值和释放。 e.g。
int x = 0;
NSString *aString = [NSString alloc]init]; <-- value store to 'aString' during its initialization is never read
// do something with aString
[aString release];
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;
或者我会使用一个自动释放的字符串,因此运行时将执行释放,即
NSString *aString = [[[NSString alloc]init]autorelease];
或者更好地使用其中一个构造函数类方法
NSString *aString = [NSString string];