NSArray @property backed by a NSMutableArray
ios, mutable, nsarray, objective-c
Solution
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
Problem
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!