将Observer添加到BOOL变量

是否可以将观察者添加到简单变量(如BOOL或NSIntegers)中,并查看它们何时发生变化? 谢谢!     
已邀请:
您可以观察在值发生变化时收到通知的密钥。数据类型可以是任何东西。对于定义为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");
    }
}
    
我相信你的意思是:如果属性发生了变化,如何从'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];
}
    
是;唯一的要求是这些变量出现的对象是那些属性的键值兼容。     
如果它们是对象的属性,那么是。 如果他们不是属性,那么没有。     

要回复问题请先登录注册