Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray @property backed by a NSMutableArray

I've defined a class where I'd like a public property to appear as though it is backed by an NSArray. That is simple enough, but in my case the actual backing ivar is an NSMutableArray:

@interface Foo {     NSMutableArray* array; } @property (nonatomic, retain) NSArray* array;  @end 

In my implementation file (*.m) I @synthesize the property but I immediately run into warnings because using self.words is the same as trying to modifying an NSArray.

What is the correct way to do this?

Thanks!

like image 472
Matty P Avatar asked Dec 06 '11 21:12

Matty P


People also ask

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .

Is NSMutableArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


1 Answers

I would declare a readonly NSArray in your header and override the getter for that array to return a copy of a private NSMutableArray declared in your implementation. Consider the following.

Foo.h

@interface Foo  @property (nonatomic, retain, readonly) NSArray *array;  @end 

Foo.m

@interface Foo ()  @property (nonatomic, retain) NSMutableArray *mutableArray  @end  #pragma mark -  @implementation Foo  @synthesize mutableArray;  - (NSArray *)array {     return [[self.mutableArray copy] autorelease]; }  @end 
like image 164
Mark Adams Avatar answered Sep 20 '22 03:09

Mark Adams