问题描述
我在接口中声明了一个只读属性,如下所示:
I have declared a readonly property in my interface as such:
@property (readonly, nonatomic, copy) NSString* eventDomain;
也许我误解了属性,但是我认为当您将其声明为readonly
时,可以在实现(.m
)文件中使用生成的setter,但是外部实体无法更改该值. 这个SO问题说,这应该发生.这就是我所追求的行为.但是,当尝试使用标准的setter或点语法在我的init方法内部设置eventDomain
时,它给了我一个unrecognized selector sent to instance.
错误.当然,我正在@synthesize
财产.尝试像这样使用它:
Maybe I'm misunderstanding properties, but I thought that when you declare it as readonly
, you can use the generated setter inside of the implementation (.m
) file, but external entities cannot change the value. This SO question says that's what should happen. That is the behavior I'm after. However, when attempting to use the standard setter or dot syntax to set eventDomain
inside of my init method, it gives me an unrecognized selector sent to instance.
error. Of course I'm @synthesize
ing the property. Trying to use it like this:
// inside one of my init methods
[self setEventDomain:@"someString"]; // unrecognized selector sent to instance error
那么我是否误解了属性的readonly
声明?还是发生了其他事情?
So am I misunderstanding the readonly
declaration on a property? Or is something else going on?
推荐答案
您需要告诉编译器您也想要一个setter.一种常见的方法是将其放在类扩展:
You need to tell the compiler that you also want a setter. A common way is to put it in a class extension in the .m file:
@interface YourClass ()
@property (nonatomic, copy) NSString* eventDomain;
@end
这篇关于Objective-C中的只读属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!