开发者

Read-only outlet?

Let's say I have a class. I would like to declare a property in the following way:

  1. From outside of the class it should be read-only if accessed programmatically;
  2. It should be possible to set the value f开发者_C百科rom the Interface Builder using an outlet;
  3. (From inside the class it should be writable, but I know how to do it).

The "solution" I came up with is to write a one-time setter:

- (void) setA: (ClassA *)a {
    if (aHaveBeenSet)
        return;
    else {
        // do what a setter have to do
        aHaveBeenSet == YES;
    }
}

But this setter still can be called from the code (though only once in effect), so it's not quite a solution.

Another way is to mark the ivar as IBOutlet and make the property readonly like this:

@interface MyClass : NSObject {
     IBOutlet ClassA *a;
}
@property (readonly) ClassA *a;
@end

But according to this answer, it's a poor style and makes memory management unclear.

Any ideas?


Someone correct me if I'm wrong, but I think the NIB loading mechanism checks for a setter method only when instantiating a .nib file at runtime. So that means you could declare your public property as readonly but write a "private" setter in your .m file:

// MyClass.h
@property (readonly, retain) IBOutlet ClassA *a;

// MyClass.m
@interface MyClass ()
@property (readwrite, retain) ClassA *a;
@end

@implementation MyClass
@synthesize a;
...
@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜