[英]How to change readonly property in category in objective-c
In my *.h file I have foo
property that is readonly. 在我的* .h文件中,我具有只读的
foo
属性。
I update that property win some other public method by using _foo = _foo + 1;
我通过使用
_foo = _foo + 1;
更新了该属性,从而赢得了其他一些公共方法_foo = _foo + 1;
Now I have category on that *.h file. 现在,我在该* .h文件上具有类别。
I need to update foo
property from category. 我需要从类别更新
foo
属性。
If I use _foo
then I got Use of undeclared identifier '_foo''
如果我使用
_foo
则Use of undeclared identifier '_foo''
If I use self.foo = 5
then I got Assignment to readonly property
如果我使用
self.foo = 5
那么我将Assignment to readonly property
I know that I can fix this by setting foo
property as readwrite, but I would like to avoid that. 我知道可以通过将
foo
属性设置为readwrite来解决此问题,但我想避免这种情况。
Question 题
How to solve it ? 怎么解决呢?
Also is it possible to set property as readonly from outside the class, but as readwrite from within the class and category ? 也可以将属性从类外部设置为只读,但从类和类别内部设置为readwrite?
That would solve this problem. 那将解决这个问题。
You could declare the property's backing instance variable in the header file as well, so the compiler can see it in the category: 您还可以在头文件中声明属性的支持实例变量,以便编译器可以在类别中查看它:
@interface MyClass : NSObject
{
int _foo;
}
@property (readonly) int foo;
@end
Explicitly declare that this variable will be used to back the property (for safety only): 明确声明此变量将用于支持属性(仅出于安全考虑):
@implementation MyClass
@synthesize foo = _foo;
...
@end
And then referencing _foo
in the category should work fine: 然后在类别中引用
_foo
应该可以正常工作:
@implementation MyClassCategory
- (void)someMethod
{
_foo++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.