I'm still pretty new to objective-c.
As far as I can understand, any object I do not get from alloc, new, copy, or mutableCopy should be开发者_Go百科 assumed to be in the autorelease pool.
I assume that also means that if I create a function that creates and returns a new instance of an object, I should place that in the autorelease pool before returning.
For example, I have a function that parses xml, and returns an object representing the data in the xml, that object should be in the autorelease pool before returning.
My primary concern is iPhone development, but a general answer would be appreciated.
You can do it both ways: either return an object that is owned by the caller, or return an object that is not owned by the caller (e.g., an autoreleased object). Regardless of which strategy you choose, follow the naming conventions. For instance,
- (NSString *)fullNameCopy {
return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
returns an NSString
object that is owned by the caller. The method name is fullNameCopy
, which follows the naming rules: a method that contains ‘copy’ in its name returns an object that’s owned by the caller. The return value is not placed in the autorelease pool.
Alternatively,
- (NSString *)fullName {
return [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName];
}
or
- (NSString *)fullName {
NSString *s = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
return [s autorelease];
}
return a string that is not owned by the caller, and the method name doesn’t contain alloc, new, or copy. The return value is autoreleased, hence it will be deallocated when the corresponding autorelease pool is drained unless the caller explicitly chooses to retain it.
That said, in your particular scenario, the second strategy — returning an object that is not owned by the caller — looks like a better solution. The caller will most likely either process the object immediately (so he won’t be interested in owning the object) or keep it in a property (which will most likely be either a copy or a retain property).
Yep, your right. If you allocated memory in your function you are also responsible for releasing it. Because you are returning the allocated object, the only way for you to release it, in this situation, is by placing it in the autorelease pool, e.g.
return [newObject autorelease];
(edit)
- You should read the Objective-C memory management guide.
- Any object returned from a
new
,alloc
orcopy
method is yours. You own it and you must release it. - Any object returned from any other method is in the autorelease pool. If you want to keep the object beyond your current scope, you must retain it.
The XML example is probably correct: If you're returning an object from a method and the name of that method does not contain new
or copy
in the name you should, by convention, return an autoreleased object.
精彩评论