iOS Memory leak

spilakalb

macrumors member
Original poster
Sep 23, 2012
40
0
Code:
str = [[NSString alloc]initWithString:@"test leak"];
str = [[NSString alloc]initWithString:@"second string"];
In above code there is a leak right? But Instruments Leak not identifying it.

But
Code:
str = [[NSMutableString alloc]initWithString:@"test leak"];
str = [[NSMutableString alloc]initWithString:@"second string"];
Here leak is identifyiing..Please explain..
 
Last edited by a moderator:

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
Don't use NSString stringWithString or initWithString.

Your code becomes:

Code:
str = @"test leak";
str = @"second string";
Do you understand why this will never leak, even though it is against the rules?

I assume you understand why the second example does leak.
 

spilakalb

macrumors member
Original poster
Sep 23, 2012
40
0
str = @"test leak";
str = @"second string";
Here @"test leak" doesn't have any refference .So it cause leak right?
 

spilakalb

macrumors member
Original poster
Sep 23, 2012
40
0
Is it mandatory to set value is nil after release, to avoid the memory leak?
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
String literals are constants. They cannot leak. They are real NSString objects but they are special and cannot leak. retain, release, autorelease for string constants have no effect.

That is why I said in #2 that that code will never leak.

Also, due to library optimizations stringWithString and initWithString using string literals will return the string literals, not new strings.