是否可以将观察者添加到简单变量(例如 BOOL 或 NSIntegers)并查看它们何时发生变化?
Thanks!
您观察键,当它们的值发生变化时会收到通知。数据类型可以是任何类型。对于定义为 Objective-C 属性的任何内容(在 .h 文件中使用 @property),这已经准备就绪,因此如果您想观察添加到视图控制器的 BOOL 属性,请按如下方式操作:
在 myViewController.h 中:
@interface myViewController : UIViewController {
BOOL mySetting;
}
@property (nonatomic) BOOL mySetting;
在 myViewController.m 中
@implementation myViewController
@synthesize mySetting;
// rest of myViewController implementation
@end
在 otherViewController.m 中:
// assumes myVC is a defined property of otherViewController
- (void)presentMyViewController {
self.myVC = [[[MyViewController alloc] init] autorelease];
// note: remove self as an observer before myVC is released/dealloced
[self.myVC addObserver:self forKeyPath:@"mySetting" options:0 context:nil];
// present myVC modally or with navigation controller here
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == self.myVC && [keyPath isEqualToString:@"mySetting"]) {
NSLog(@"OtherVC: The value of self.myVC.mySetting has changed");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)