是否可以将观察者添加到简单变量(如BOOL或NSIntegers)中,看看它们何时发生变化?
谢谢!
答案 0 :(得分:22)
您会观察到价值变化时要通知的密钥。数据类型可以是任何东西。对于定义为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");
}
}
答案 1 :(得分:5)
我相信你的意思是:如果属性发生了变化,如何从'change'字典中获取INT或BOOL值。
你可以这样做:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"mySetting"])
{
NSNumber *mySettingNum = [change objectForKey:NSKeyValueChangeNewKey];
BOOL newSetting = [mySettingNum boolValue];
NSLog(@"mySetting is %s", (newSetting ? "true" : "false"));
return;
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
答案 2 :(得分:1)
是;唯一的要求是这些变量出现的对象符合这些属性的键值。
答案 3 :(得分:-2)
如果它们是对象的属性,那么是。
如果它们不是属性,那么没有。