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

依然范特西╮ 提交于 2019-12-31 00:57:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21109083/how-to-make-an-immutable-readonly-property-in-the-header-file-h-a-mutable-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!