Reputation: 2428
To me, the following code looks like it will create a leak -- I might be wrong about this though:
-(NSString*) myString{
NSString* foo = @"bar";
return foo;
}
My question is:
1) Will is create a memory leak as foo
is not released?
2) If it IS a memory leak then how do I avoid it?
Upvotes: 2
Views: 97
Reputation: 10014
Short answer. This code will not give a leak.
Long answer:
With NSString it is not always visible leak, because of strings intern and because you do not call alloc/new/copy methods. But yes, this is a classic point of memory leak in general.
There are two ways of dealing with it.
NSString *foo = [NSString stringWithString:@"bar"];
And this one is similar to:
NSString *foo = [[[NSString alloc] initWithString:@"bar"] autorelease];
So, you will return an object, that has retain count 1, but is autoreleased. So, when NSAutoreleasePool will be drained, this object will go away.
Upvotes: 3
Reputation: 35384
It is not a leak. @"bar" is a statically allocated string and thus foo doesn't need to be retained. You can handle these strings like autoreleased objects although they will resist in memory for the runtime of the application.
You can turn it into a leak by returning [foo retain]
or [foo copy]
.
Technically it makes no sense to retain static variables. But if you copy them, you have to release them.
Upvotes: 4