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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With