Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray as @property with readonly

Tags:

objective-c

Suppose I have something like this:

@property (readonly) NSMutableArray *someArray;

Can I modify [obj someArray] even though the @property is set to readonly?

like image 870
Sam Lee Avatar asked Dec 14 '22 05:12

Sam Lee


2 Answers

Yes, you can modify its contents. The readonly only applies to the pointer itself - in that way, it is not like C++'s const.

Basically, saying "readonly" just means "don't translate a.someArray = foo into [a setSomeArray:foo]". That is, no setter is created.

(Of course, if you wanted to prevent modification, you'd just use an NSArray instead.)

like image 130
Jesse Rusak Avatar answered Dec 27 '22 11:12

Jesse Rusak


The contents of someArray are modifiable, although the property is not (i.e. a call cannot change the value of the someArray instance variable by assigning to the property). Note, this is different from the semantics of C++'s const. If you want the array to be actually read-only (i.e. unmodifiable by the reader), you need to wrap it with a custom accessor. In the @interface (assuming your someArray property)

@property (readonly) NSArray *readOnlyArray;

and in the @implementation

@dynamic readOnlyArray;

+ (NSSet*)keyPathsForValuesAffectingReadOnlyArray {
  return [NSSet setWithObject:@"someArray"];
}
- (NSArray*)readOnlyArray {
  return [[[self someArray] copy] autorelease];
}

Note that the caller will still be able to mutate the state of objects in the array. If you want to prevent that, you need to make them immutable on insertion or perform a depp-copy of the array in the readOnlyArray accessor.

like image 45
Barry Wark Avatar answered Dec 27 '22 11:12

Barry Wark