Skip to content
This repository has been archived by the owner on Dec 12, 2018. It is now read-only.

Returning NSMutableArray as NSArray #70

Closed
gamenerds opened this issue Feb 21, 2014 · 3 comments
Closed

Returning NSMutableArray as NSArray #70

gamenerds opened this issue Feb 21, 2014 · 3 comments

Comments

@gamenerds
Copy link

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).

@supermarin
Copy link
Owner

@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.

@gamenerds
Copy link
Author

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.

@supermarin
Copy link
Owner

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants