Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to observe a readonly property of an object in Cocoa Touch?

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?

like image 965
user53937 Avatar asked Feb 14 '09 19:02

user53937


People also ask

What is read only property in IOS?

Read-only means that we can access the value of a property but we can't assign any value to it.

What is readonly in Objective C?

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.


3 Answers

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.

like image 165
Barry Wark Avatar answered Sep 22 '22 09:09

Barry Wark


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
like image 23
Anton Holmberg Avatar answered Sep 20 '22 09:09

Anton Holmberg


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.

like image 31
wisequark Avatar answered Sep 23 '22 09:09

wisequark