supermarin/ObjectiveSugar

Returning NSMutableArray as NSArray

Closed this issue · 3 comments

Hey guys, I see multiple places where the method signature says the return type is NSArray but the actual object being returned is NSMutableArray. This is a potential problem because the returned object will still respond to NSMutableArray messages. It is Apple's recommendation and standard practice to make a non-mutable copy of the array before returning. So:

NSMutableArray *myArray = ...
// fill the array here
return myArray;

should become

NSMutableArray *myArray = ...
// fill the array here
return [myArray copy];

You can also use [NSArray arrayWithArray:myArray] instead of [myArray copy](I think "copy" in this case just makes a call to arrayWithArray anyway, so using arrayWithArray cuts out a directive or two).

@gamenerds we've had this discussion before, and kinda decided to leave it mutable just for memory reasons.

Not sure what would be the use case of damaging yourself here, if you have some examples I'm open for discussion.

It's definitely your call in the end; it's hard to come up with a good example that doesn't involve shenanigans that shouldn't be used anyway.

It's more a question of transparency. You're veiling the real type of an object, saying that it's NSArray when, in fact, it is not an NSArray. I am not sure what you mean by memory issues seeing as the NSMutableArray reference would get deallocated anyway.

But as long as you've made a conscious decision to keep things this way, I'll close this issue. I thought perhaps it was accidental.

It will get deallocated; but if it's really a huge array, and if there's many of them, at one point I'd expect you'll need double amount of memory space before the mutable ones get deallocated