use*_*937 19 iphone cocoa-touch properties key-value-observing
我试图观察UINavigationController的(readonly)visibileViewController属性但没有成功.我能够成功地观察到我自己定义的读写属性,以便在另一个类上进行测试.
是否有可能观察到readonly属性?
Ant*_*erg 15
是.在您自己的类中实现它的一种简单方法是在.h文件中将该属性声明为readonly,并在.m文件的私有接口中将其重新声明为可写.这样您就可以合成并自动处理更改通知.
在.h文件中:
@interface MyClass : NSObject
@property (nonatomic, readonly) BOOL foo;
@end
Run Code Online (Sandbox Code Playgroud)
在.m文件中
@interface MyClass ()
@property (nonatomic, readwrite) BOOL foo;
@end
@implementation MyClass
@synthesize foo;
- (void)bar {
// Observers will see the change
self.foo = YES;
}
@end
Run Code Online (Sandbox Code Playgroud)
Nic*_*dad -2
使用NSKeyValueObserving这绝对是可能的。属性实际上有 getter/setter 实现,它们只是由编译器通过 Objective-C 类实现中的 @synthesize 关键字为您完成。由于键值观察协议基于 Objective-C 中的标准 getter/setter 约定,因此观察属性效果很好。文档(上面链接)甚至按名称提到了类属性:
“NSKeyValueObserving (KVO) 非正式协议定义了一种机制,允许对象收到其他对象指定属性更改的通知。”