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

前端 未结 1 591
北恋
北恋 2021-01-19 18:30

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

相关标签:
1条回答
  • 2021-01-19 19:17

    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.

    0 讨论(0)
提交回复
热议问题