简体   繁体   中英

How to change readonly property in category in objective-c

In my *.h file I have foo property that is readonly.
I update that property win some other public method by using _foo = _foo + 1;

Now I have category on that *.h file.
I need to update foo property from category.

If I use _foo then I got Use of undeclared identifier '_foo''
If I use self.foo = 5 then I got Assignment to readonly property

I know that I can fix this by setting foo property as readwrite, but I would like to avoid that.

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

@implementation MyClassCategory

- (void)someMethod
{
    _foo++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM