我可以使用公共getter和私有setter创建属性吗? [英] Can I create properties with a public getter and private setter?

查看:123
本文介绍了我可以使用公共getter和私有setter创建属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的实例变量使用属性,但在许多情况下,我只想让类本身有权访问setter。我希望我可以做这样的事情:

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 this:

Foo.h:

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

Foo.m:

#import "Foo.h"

@interface Foo ()
@property (copy) NSString *bar;
@end

@implementation Foo
@synthesize bar;
@end

但这会产生警告:

Foo.m:4: warning: property ‘bar’ attribute in ‘Foo’ class continuation does not match class ‘Foo’ property

我可以看到它的抱怨,但它仍然是一个有用的成语。有没有其他方法来完成这个没有写我自己的setters?

I can see what it's complaining about, but it still seems like a useful idiom. Is there some other way to accomplish this without writing my own setters?

推荐答案

您的方法是正确的,但重新声明< c $ c> @property bar 在类扩展中必须匹配原始声明,除了readwrite和readonly。所以这将工作:

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

(回忆默认值为 code>属性,而不是 copy )。

这篇关于我可以使用公共getter和私有setter创建属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆