将观察者添加到BOOL变量 [英] Add Observer to BOOL variable

查看:89
本文介绍了将观察者添加到BOOL变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将观察者添加到简单变量(例如BOOL或NSIntegers)中,并查看它们何时更改?

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

谢谢!

推荐答案

您观察到键的值更改时会得到通知的键.数据类型可以是任何东西.对于定义为Objective-C属性(在.h文件中带有@property)的任何内容,都可以使用,因此,如果要观察添加到视图控制器中的BOOL属性,请按以下步骤进行操作:

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:

在myViewController.h中:

in myViewController.h:

@interface myViewController : UIViewController {
    BOOL      mySetting;
}

@property (nonatomic)    BOOL    mySetting;

在myViewController.m

in myViewController.m

@implementation myViewController

@synthesize mySetting;

// rest of myViewController implementation

@end

在otherViewController.m中:

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

这篇关于将观察者添加到BOOL变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆