objective-c ARC readonly properties and private setter implementation

前端 未结 2 2036
心在旅途
心在旅途 2021-02-01 04:39

Prior to ARC, if I wanted a property to be readonly to using it but have it writeable within the class, I could do:

// Public declaration
@interface SomeClass :          


        
相关标签:
2条回答
  • 2021-02-01 04:50

    You can redeclare your property as readwrite in interface extension:

    @interface SomeClass()
    @property (nonatomic, strong, readwrite) NSString *myProperty;
    @end
    
    0 讨论(0)
  • 2021-02-01 05:08

    Yes, that is adequate, but you don't even need that much.

    You can do

    - (void)setMyProperty:(NSString *)newValue
    { 
          myProperty = newValue;
    }
    

    The compiler will do the right thing here.

    The other thing though, is you don't even need THAT. In your class extension you can actually respecify @property declarations.

    @interface SomeClass : NSObject
    @property (nonatomic, readonly, strong) NSString *myProperty;
    @end
    
    @interface SomeClass()
    @property (nonatomic, readwrite, strong) NSString *myProperty;
    @end
    

    Doing that, you just need to synthesize and you have a private setter that is synthesized for you.

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