Add Observer to BOOL variable

前端 未结 4 1965
半阙折子戏
半阙折子戏 2021-02-08 13:48

Is it possible to add observers to simple variables such as BOOLs or NSIntegers and see when they change?

Thanks!

4条回答
  •  星月不相逢
    2021-02-08 14:40

    I believe what you meant was: How to get INT or BOOL value from the 'change' dictionary if the property has changed.

    You can simply do it this way:

    - (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];
    }
    

提交回复
热议问题