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