And*_*rei 9 iphone objective-c addobserver
是否可以将观察者添加到简单变量(如BOOL或NSIntegers)中,并查看它们何时发生变化?
谢谢!
XJo*_*nes 22
您可以观察在值发生变化时收到通知的密钥.数据类型可以是任何东西.对于定义为Objective-C属性的任何内容(在.h文件中使用@property),如果您想要观察添加到视图控制器的BOOL属性,则可以执行此操作,如下所示:
在myViewController.h中:
@interface myViewController : UIViewController {
BOOL mySetting;
}
@property (nonatomic) BOOL mySetting;
Run Code Online (Sandbox Code Playgroud)
在myViewController.m中
@implementation myViewController
@synthesize mySetting;
// rest of myViewController implementation
@end
Run Code Online (Sandbox Code Playgroud)
在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");
}
}
Run Code Online (Sandbox Code Playgroud)
我相信你的意思是:如果属性发生了变化,如何从'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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16047 次 |
| 最近记录: |