How to make an immutable readonly property in the header file (.h), a mutable readwrite property in implementaion (.m)

cocoa, cocoa-touch, ios, iphone, objective-c

Solution

You need a separate private mutable variable in your implementation. You can override the getter to return an immutable object.

@interface MyObject () {
  NSMutableDictionary *_mutableJSONData;
}
@end

@implementation MyObject 

// ...

-(NSDictionary *)JSONData {
   return [NSDictionary dictionaryWithDictionary:_mutableJSONData];
}

// ...
@end

No need to implement the setter, as it is `readonly`.

Problem

I have an object that holds a dictionary `JSONData`. From the header file, and to the other classes that'll access it, I want this property to only be read-only and immutable. ``` @interface MyObject : NSObject @property (readonly, strong, nonatomic) NSDictionary *JSONData; @end ``` However, I need it to be `readwrite` and mutable from the implementation file, like this, but this doesn't work: ``` @interface MyObject () @property (readwrite, strong, nonatomic) NSMutableDictionary *JSONData; @end @implementation MyObject // Do read/write stuff here. @end ``` Is there anything I can do to enforce the kind of abstraction I'm going for? I looked at the other questions and while I already know how to make a property `readonly` from `.h` and `readwrite` from `.m`, I can't find anything about the difference in mutability.

Original source

Related problems