NSMutableArray as @property with readonly

Suppose I have something like this:

@property (readonly) NSMutableArray *someArray; 

Can I change [obj someArray] even if @property is set to readonly?

+4
source share
2 answers

Yes, you can change its contents. Readonly applies only to the pointer itself - thus, it does not look like C ++ const .

Basically, "readonly" simply means "don't translate a.someArray = foo to [a setSomeArray:foo] ". That is, a setter is not created.

(Of course, if you want to prevent modification, you simply use NSArray .)

+10
source

The contents of someArray can be changed, although the property is not (i.e., the call cannot change the value of the instance variable someArray , assigning it to the property). Note that this is different from the semantics of C ++ const . If you want the array to be actually readable (i.e. not readable), you need to wrap it with a special accessor. In @interface (assuming your someArray property)

 @property (readonly) NSArray *readOnlyArray; 

and in @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 change the state of the objects in the array. If you want to prevent this, you must make them immutable when pasting, or make a depp copy of the array in Access readOnlyArray .

+3
source

All Articles