NSArray @property backed by a NSMutableArray

Matty P picture Matty P · Dec 6, 2011 · Viewed 11.6k times · Source

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!

Answer

Mark Adams picture Mark Adams · Dec 6, 2011

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