views:

34

answers:

2

How do you release the memory in this situation? Do you have to?

- (NSString *) whatHappensHere {
 NSMutableString * mutableString = [[NSMutableString alloc] initWithString:@"Hello"];
     // ....
        // more code ...
        // ...
 return mutableString;
}
+2  A: 

With autorelease

- (NSString *) whatHappensHere {
 NSMutableString * mutableString = [[NSMutableString alloc] initWithString:@"Hello"];

[mutableString autorelease];
 return mutableString;
}
willcodejavaforfood
Alternatively, allocate, initialise and autorelease all on the one line; then you can [more easily] have multiple return statements if you have to exit prematurely.
dreamlax
Wouldn't an even better alternative be to rewrite it like so: `NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];` since that takes care of all three with one message?
jlehr
That works as well. When you are learning it might be good to be explicit with your memory management though
willcodejavaforfood
A: 

As willcodejavaforfood said, the convention is that any newly-allocated object returned from a method should be autorelease'd before being returned. This tells the Objective-C runtime that if nobody takes ownership of it with retain before (in most cases) the current iteration of the application event loop ends, it should be freed.

If it's just used locally in the calling function or returned up the stack, that works great and it gets freed sooner or later. If someone ends up wanting to keep it around, then they have to retain it and so will know they have to release it themselves later on.

(In fact, most of the non-init* utility constructors for ObjC base classes like strings, etc, do just that, or at least something functionally equivalent.)

Walter Mundt