Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose an NSMutableArray as an NSArray as a return type from a method

Tags:

ios

I have a model class which contains an NSMutable array of objects. The controller classes need to have access to this array, however that access should be read only.

How should this be implemented? Should the model expose the array as a (readonly) NSMutable array and use consts, or expose it as an NSArray? If the latter how can the NSArray be created efficiently from the NSMutableArray i.e. how should the NSArray contain a reference to the NSMutableArray/its contents rather than have duplicate copies? (the NSMutableArray is guaranteed to persist in memory while the controllers access it).

like image 971
Gruntcakes Avatar asked Dec 04 '22 18:12

Gruntcakes


1 Answers

You can just return your NSMutableArray directly:

- (NSArray *)method
{
    return myMutableArray;
}

NSMutableArray is a subclass of NSArray, so the controllers will be able to perform all of the NSArray operations on it already. If you're really concerned that somebody might be trying to pull tricks on you, you could use:

return [NSArray arrayWithArray:myMutableArray];

to return an immutable copy.

like image 63
Carl Norum Avatar answered Dec 14 '22 23:12

Carl Norum