Reputation: 613
I'm new to Objective-C and I am having some difficulty with understanding memory management.
So let's say I have a class and an instance variable of type NSString* that isn't tied to a property. Would this situation leak memory?
myString = [[NSString alloc] init];
//more program stuff
myString = [[NSString alloc] init];
Should I have called [myString release]
before I set myString equal to a new object? Will this sort of code leak memory? Do I have to release an object like this every time I have the pointer point to a different object?
Upvotes: 0
Views: 62
Reputation: 28572
Yes, you need to release the first object before you reassign your variable to point to the second object. Otherwise, you lose track of your first object and you leak it because you can't release it. You are responsible for releasing the object because you created it (via alloc
) as explained in the Memory Management Rules.
Also, bear in mind that [[NSString alloc] init]
is creating an empty and immutable string (NSString
s are immutable meaning that they can not be changed after creation). There is little point in doing this.
Upvotes: 1
Reputation: 5539
For future, stick to the simple rule that for every alloc
/copy
/retain
you should pair it with a release
.
Upvotes: 2
Reputation: 48398
First, Apple's Memory Management Programming Guide is a great place to look for examples and instructions about memory management.
Now to your question. When you call myString = [[NSString alloc] init];
you are reassigning the pointer myString
and as such lose access to the original NSString
, thus creating a memory leak.
The general rule of thumb here is that for every alloc
you should have a release
and these must alternate appropriately. If you do
myString = [[NSString alloc] init];
// ...
myString = [[NSString alloc] init];
// ...
[myString release];
[myString release];
you are releasing the same instance twice which results in overreleasing and an error BAD-ACCESS. The correct thing to do is
myString = [[NSString alloc] init];
// ...
[myString release];
myString = [[NSString alloc] init];
// ...
[myString release];
so that each instance is correctly released.
Upvotes: 2
Reputation: 34263
Yes this will leak.
By allocating and assigning another NSString
instance to the same variable myString
, you lose reference to the original content of myString
and therefore the ability to send it a release message.
Both, the Clang static analyzer and the Leaks instrument should uncover this leak.
Upvotes: 1