I hardly ever see the second one used and I wonder why?
- Neither would it break support for situations where an
NSArrayis expected (as it’s a subclass). - Nor would it break encapsulation by revealing mutable internals.
Under the precondition that it’s never a mutable ivar that’s returned, (which should be common sense anyway)
I can right now only think of advantages of using the second.
- It actually is mutable. And muting is safe here, so why prevent it?
- No need to call
[[[foo fooBar] mutableCopy] autorelease], which needlessly allocates additional memory and needlessly wastes time.
Here are the method variations:
- (NSArray *)fooBar {
NSMutableArray *fooArray = [NSMutableArray array];
//populate fooArray
return fooArray;
}
- (NSMutableArray *)fooBar {
NSMutableArray *fooArray = [NSMutableArray array];
//populate fooArray
return fooArray;
}
I’m asking as my project has a bunch of methods with the same pattern.
And in most of the times the returned array will be modified afterwards (merged, edited, etc).
So I think it should be totally fine to return NSMutableArrays, yet nobody seems to be doing it.
NSMutableArray, NSMutableSet, NSMutableDictionary… it’s basically the same deal.
I suppose the first variation was preferred because polymorphism was preferred.
In either case, both methods return an instance of
NSMutableArray, the only difference being that the first one hides that fact from the caller. In other words, the first variation is not safer than the second. It’s essentially using polymorphism to tell the caller that any type ofNSArraymight be returned. If you need that kind of flexibility in your code, it definitely has it’s advantages. (e.g., if one day, for whatever reason, you need to return a customNSArraysubclass, your code won’t break at that level).However, you seem to prefer communicating intent to the caller – i.e. that you actually return mutable arrays – which is also OK. To make everyone happy (if there is such thing anyways…), I suggest renaming the 2nd method to:
As a side note, I think that the following is a slightly more efficient way to convert an existing immutable array into a mutable one:
(correct me if I’m wrong on that assumption).
I hope this answers your question…