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?
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 pointermyStringand as such lose access to the originalNSString, thus creating a memory leak.The general rule of thumb here is that for every
allocyou should have areleaseand these must alternate appropriately. If you doyou are releasing the same instance twice which results in overreleasing and an error BAD-ACCESS. The correct thing to do is
so that each instance is correctly released.