When returning an NSArray
(or NSDictionary
, etc.) from a method that builds the array on the fly using an NSMutableArray
, what is the standard way to do this and avoid random memory leaks when using ARC?
For example, let's say we had some class with a list of names, and we wanted to manually filter and grab all of the names that started with a given letter:
- (NSArray *)getNamesByFirstLetter:(NSString *)firstLetter
{
NSMutableArray *returnValue = [[NSMutableArray alloc] init];
for(id item in self.names)
{
if([item hasPrefix:firstLetter])
{
[returnValue addObject:item];
}
}
return returnValue; // just return the above array
}
When it comes to returning the value, I can think of four possible ways to do it:
Return the
NSMutableArray
directly (as above)return returnValue;
Return a
copy
return [returnValue copy];
Return using
NSArray arrayWithArray
:return [NSArray arrayWithArray:returnValue];
Create an
NSArray
, manually set theNSMutableArray
tonil
:NSArray *temp = [NSArray arrayWithArray:returnValue]; // could use [returnValue copy] here too returnValue = nil; return temp;
When a program is using ARC, is there any real difference between these four methods, or does it just come down to personal preference?
Also, besides possible memory leaks, are there any other implications when using one method over another?
Note, if this is a duplicate, let me know, and I'll take the question down. I tried searching, but had a hard time trying to condense the issue down to a few search terms.