只读插座?

发布于 2024-11-07 23:30:06 字数 758 浏览 2 评论 0原文

假设我有课。我想通过以下方式声明一个属性:

  1. 从类外部,如果以编程方式访问,它应该是只读的;
  2. 应该可以使用插座从 Interface Builder 设置值;
  3. (从类内部它应该是可写的,但我知道该怎么做)。

我想出的“解决方案”是编写一个一次性的setter:

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

但是这个setter仍然可以从代码中调用(尽管只有效一次),所以它不完全是一个解决方案。

另一种方法是将 ivar 标记为 IBOutlet 并使属性 readonly 如下所示:

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

但根据 这个答案,这是一种糟糕的风格,并且使内存管理不清楚。

有什么想法吗?

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 from 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末が日狂欢 2024-11-14 23:30:06

如果我错了,有人会纠正我,但我认为 NIB 加载机制仅在运行时实例化 .nib 文件时检查 setter 方法。因此,这意味着您可以将公共属性声明为只读,但在 .m 文件中写入“私有”设置器:

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

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

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文