Add Observer to BOOL variable

前端 未结 4 1955
半阙折子戏
半阙折子戏 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:46

    You observe keys to be notified when their value changes. The data type can be anything. For anything defined as an Objective-C property (with @property in the .h file) this is ready to go so if you want to observe a BOOL property you add to a view controller you do it as follows:

    in myViewController.h:

    @interface myViewController : UIViewController {
        BOOL      mySetting;
    }
    
    @property (nonatomic)    BOOL    mySetting;
    

    in myViewController.m

    @implementation myViewController
    
    @synthesize mySetting;
    
    // rest of myViewController implementation
    
    @end
    

    in 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");
        }
    }
    

提交回复
热议问题