I’m declaring an ivar of type NSString on a class. To initialize the value of this ivar I use the following code:
NSString *myVar;
-(void)inAnyMethod
{
myVar = [NSString stringWithFormat:@"%@",theValue];
}
Do I have to release this ivar? According to my understanding, it is not my responsibility. But in most cases, strings that I use in this manner cause leaks.
What am I missing?
In addition to Oscar Gomez answer, note that when you use class methods (those methods with plus sign that you can find in the documentation and are not included in Oscar Gomez list, e.g.
stringWithFormatis one of them), you have not to worry about memory management. If you create your own class method, you should do the same: return an autorelease object.Regarding your code, it cannot work if you simply assign your ivar to the
NSStringobject (returned from that method). In fact, at some point of your application cycle, the object will be released (it has been put in a pool) and your ivar will not reference any object anymore.The trick: create a
@propertywith acopypolicy or send acopymessage like the following:Copy is normally used when a class has subclasses of mutable type. Otherwise use
retain. Once done, you have the possession for that object and you have to remember to release it. If you don’t do it you cause a leak.P.S. Since Xcode 4.2 there is a new compiler feature called ARC.
Hope it helps.