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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With