Objective-C : (private / public properties) making a property readonly for outside class calls and readwrite for self calls

后端 未结 4 903
野的像风
野的像风 2020-12-04 18:01

Would you know a way to make a property readonly for outside calls and readwrite for inside calls ?

I\'ve read times ago somthing that seemed like

In the .h

相关标签:
4条回答
  • 2020-12-04 18:20

    This issue is largely eliminated if you're moving to ARC. Instead of two property declarations, you'd declare it once in the header.

    @property(nonatomic, readonly) NSDate* theDate;
    

    And then in the class extension, simply declare a __strong instance variable.

    @interface TheClassName()
    {
        __strong NSDate* _theDate;
    }
    @end
    

    And synthesize them appropriately in the implementation

    @implementation TheClassName
    @synthesize theDate = _theDate;
    

    Now you can set the instance variable.

    _theDate = [NSDate date];
    

    And ARC will magically inline the appropriate retain/release functionality into your code to treat it as a strong/retained variable. This has the advantage of being faster than the old style (retain) properties as well as ARC inlines the retain/release code at compile time.

    0 讨论(0)
  • 2020-12-04 18:24

    In the .m, you shouldn't put @property again. I'm not sure what effect that has, though. Did you mean to use @synthesize?

    Note that theDate will be read/write inside the class implementation anyway, regardless of being readonly to the outside world.

    0 讨论(0)
  • 2020-12-04 18:28

    In your .h:

    @property(nonatomic, retain, readonly) NSDate* theDate;
    

    In your .m:

    @interface TheClassName()
    @property(nonatomic, retain, readwrite) NSDate* theDate;
    @end
    
    0 讨论(0)
  • 2020-12-04 18:42

    If the property is backed by a variable, the variable is read-write from inside the class be default. Make the property read-only, and your design goal will be met. Inside the class, refer to the variable without prepending self..

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