Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
MLQ Avatar asked Mar 21 '23 23:03

MLQ


1 Answers

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.

like image 126
Mundi Avatar answered Apr 05 '23 23:04

Mundi