I often find myself implementing methods that create a bunch of objects in a loop and return them in a non-mutable array. I'd usually write something like this:
- (NSArray *)myObjects {
NSMutableArray *_temporaryArray = [NSMutableArray array];
for (id foo in foos) {
// ...
// create `myObject` from the information in `foo`
// ...
[_temporaryArray addObject:myObject];
}
return [NSArray arrayWithArray:_temporaryArray];
}
Somehow this pattern doesn't feel very elegant (creating a temporary mutable instance seems to be an overhead). So now I'm looking for better implementations depending on the use case.
What would be the best implementations for these cases:
- focus on performance
- focus on memory consumption
- focus on code brevity.
[NSMutableArray copy]to return an immutable collection. Unless you've profiled your application and found this method to be a huge bottleneck, focus on correctness and safety rather than trying to optimize unnecessarily. What is contained in foos? Can you return an array literal containing all of the myObjects?