Scenario- I have a method that returns an object retrieved from an NSMutableArray similar to the following code which has been simplified (assume that "myArray" and "currentIndex" are iVars for the class wherein this method resides):
- (MyObject *)getFromArray
{
return [myArray objectAtIndex:currentIndex];
}
Should I be tacking on a call to autorelease like so?
- (MyObject *)getFromArray
{
return [[myArray objectAtIndex:currentIndex] au开发者_JAVA技巧torelease];
}
I know that autorelease is called on the object by the array as it returns said object, but my understanding is that the autoreleased object is only valid for the duration of the caller's scope, in this case, the method above. So, would tacking on the autorelease (as shown above in the 2nd code snippet) be the correct way to make sure the object in question is valid for the caller of my method? Just trying to make sure that my reasoning and understanding of how autorelease works is correct.
Thanks!
Should I be tacking on a call to autorelease?
No! Always follow the simple memory management rules: if you don't own it (by alloc
, new
, copy
, or retain
), you must not (auto)release it.
I know that autorelease is called on the object by the array as it returns said object
That assumption is wrong. The array just returns the object, it doesn't release it. (It might actually call [[... retain] autorelease]
on the object but that's another matter.) The array will only release the object when you remove the object from the array or when the array itself gets deallocated.
精彩评论