Can I create properties with a public getter and private setter?

前端 未结 2 1645
孤独总比滥情好
孤独总比滥情好 2020-12-30 04:53

I\'d like to use properties for my instance variables, but in many cases, I only want the class itself to have access to the setter. I was hoping I could do something like

相关标签:
2条回答
  • 2020-12-30 05:36

    Your approach is correct, but the redeclaration of @property bar in the class extension must match the original declaration except for readwrite vs. readonly. So this will work:

    Foo.h

    @interface Foo {
      NSString *bar;
    }
    @property (copy,readonly) NSString *bar;
    @end
    

    Foo.m:

    #import "Foo.h"
    
    @interface Foo ()
    @property (copy,readwrite) NSString *bar;
    @end
    
    @implementation Foo
    @synthesize bar;
    @end
    

    (recall that the default is assign for properties, not copy).

    0 讨论(0)
  • 2020-12-30 05:43

    When Barry says "the default is retain for properties" he means that retain should be specified like this:

    @property (retain) NSDate *endDate;
    

    If they are left like this:

    @property NSDate *endDate;
    

    assign is assumed by the compiler.

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