I've attempted to observe the (readonly) visibileViewController property of a UINavigationController with no success. I was able to successfully observe a readwrite property I defined myself for testing purposes on another class.
Is it possible to observer readonly attributes?
Read-only means that we can access the value of a property but we can't assign any value to it.
The readonly means simply that no setter method was synthesized, and therefore using the dot notation to set a value fails with a compiler error. The dot notation fails because the compiler stops you from calling a method (the setter) that does not exist.
Yes, it is possible to observe read-only properties. However, if the object that declares that property makes changes to the value of that property in a way that is not Key-Value Observing compliant (e.g. changes the value of the instance variable backing that property directly without seding willChangeValueForKey:
and didChangeValueForKey:
notifications) then observers will not automatically be notified by the KVO system. If you can verify that the value of this property is changing and your observers are not being notified, I would (1) post some code here or elsewhere so that others can help you find your bug and (2) if there is no bug in your code, file a bug on Apple's radar.
Yes. An easy way to implement it in your own class is to declare the property as readonly in the .h file and redeclare it as writable in the private interface in the .m file. That way you can synthesize and get the change notifications handled automatically.
In the .h file:
@interface MyClass : NSObject
@property (nonatomic, readonly) BOOL foo;
@end
In the .m file
@interface MyClass ()
@property (nonatomic, readwrite) BOOL foo;
@end
@implementation MyClass
@synthesize foo;
- (void)bar {
// Observers will see the change
self.foo = YES;
}
@end
You can certainly observe readonly properties but be aware that in order for KVO to work you need to be KVC compliant - which means using either the setter/getter for a property (since you're readonly, you don't get a setter for free via @synthesize
) or the property's -setValue:forKey:
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With