How to set NSMutableArray as NSArray as return type from method

I have a model class that contains an NSMutable array. Controller classes must have access to this array, however this access should be read-only.

How should this be implemented? Should the model display the array as an (readonly) NSMutable array and use consts or expose it as an NSArray? If the latter, how can NSArray be efficiently created from NSMutableArray, then how will NSArray contain a reference to the contents of NSMutableArray / its contents, and not have duplicates? (It is guaranteed that the NSMutableArray will remain in memory while the controllers access it).

+4
source share
5 answers

You can simply return your NSMutableArray directly:

 - (NSArray *)method { return myMutableArray; } 

NSMutableArray is a subclass of NSArray , so controllers will be able to perform all NSArray operations on it already. If you are really worried that someone might be trying to impose tricks on you, you can use:

 return [NSArray arrayWithArray:myMutableArray]; 

to return an immutable copy.

+11
source

Not only NSMutableArray. If you think that defining a property as read only makes the object immutable, it is not.

Derive the read-only property of type NSArray, and return the new array in accessor as follows:

 return [NSArray arrayWithArray:mutableArray]; 

Note that the objects in the array, if they are mutable, will still be mutable.

+2
source

If you want to continue transferring your mutable array, but want to make sure that another method does not overwrite the existing array, you can always pass a copy

 return [myMutableArray copy]; 

This way you return the type NSArray (since NSMutableArray is a subclass) and make sure that myMutableArray itself does not receive the fake.

+2
source

NSMutableArray inherits from NSArray, so there is nothing to do to show NSMutableArray as an NSArray, except (possibly implicitly) for it. Note that this is still the same object, so if someone wants to be smart, he can knock it down or even just try to call NSMutableArray methods on it.

+1
source

While this may be excessive, you can create your own custom class that has the @private ivar attribute, and then you can create readonly properties / methods just for data access.

ie (fragment implementation):

 @interface CustomArray : NSObject { @private NSArray *array; } @end - (id)initWithNSArray:(NSMutableArray *)array; - (id)getObjectAtIndex:(int)index; @implementation // implement methods here @end 
0
source

Source: https://habr.com/ru/post/1388643/


All Articles