Objective-C memory management: how do you release the memory when you return an allocated instance?
How do you release the memory in this situation? Do you have to?
- (NSString *) whatHappensHere {
NSMutableString * mutableString = [[NSMutableString alloc] initWithString:@"Hello"];
// ....
/开发者_StackOverflow/ more code ...
// ...
return mutableString;
}
With autorelease
- (NSString *) whatHappensHere {
NSMutableString * mutableString = [[NSMutableString alloc] initWithString:@"Hello"];
[mutableString autorelease];
return mutableString;
}
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.)
精彩评论