Dead Store and Potential Leak of NSString in Xcode
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 sto开发者_JAVA百科re 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.
You shouldn't allocate NSString
for aString
, since you assign to aString
in the if
part.
This should be enough:
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;
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.
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;
Or I woulduse an autoreleased string so hat the runtime will do the releasing i.e.
NSString *aString = [[[NSString alloc]init]autorelease];
or better use one of the constructer class methods
NSString *aString = [NSString string];
精彩评论