objective-c ARC readonly properties and private setter implementation

前端 未结 2 2035
心在旅途
心在旅途 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 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.

提交回复
热议问题