[英]Detecting when an object in a property did change Objective C
我有一个问题,我想答案是否定的,但是我想确定。 当一个类的属性值从另一个类更改时,有什么方法可以触发方法? 在iOS中,例如:
我有FirstViewController
,它是从服务器获取的NSString
并将其另存为@property NSString helloString
。 但是它也使用NSSUserDefaults
将其保存在本地,因此,当用户进入应用程序时,他将看到本地保存的最后一个helloString
,并且当服务器应答时(例如5秒钟后),它将更新此helloString
属性。
试想一下,用户进入到SecondViewController
(这里我们通过helloString
与prepareForSegue
在FirstViewController
并保存为一个属性SecondViewController
)。 SecondViewController
显示保存helloString
,并且5秒后服务器应答并更新helloString
财产FirstViewController
(当然到的SecondViewController
)。
当FirstServerController
helloString
值更改时,是否有任何方法(我认为我可以使用NSNotificationCenter
)来触发SecondServerController
的方法?
编辑:
志愿是不是一个有效的选择,因为如果我们有一个ThirdViewController
和用户从去FirstViewController
到SecondViewController
终于ThirdViewController
,然后回去FirstViewController
通过去SecondViewcontroller
,在[FirstViewController removerObserver:forKeyPath:]
方法就是里面SecondViewController
会崩溃,因为FirstViewController
已从内存中释放。
感谢您的时间。
实际上,答案是肯定的,您可以通过键值观察做到这一点。
在prepareForSegue中,您可以添加观察者:
[self addObserver:destinationViewController forKeyPath:@"helloString" options:<#(NSKeyValueObservingOptions)#> context:NULL];
现在,当helloString更改时,将在SecondViewController中调用observeValueForKeyPath:ofObject:change:context:
方法。
在您的情况下,KVO会显得过大。 您可以简单地覆盖属性的setter方法。
例如,在SecondViewController.h中,您具有以下属性:
@property (strong, nonatomic) NSString *helloString;
在您的SecondViewController.m文件中,添加方法:
-(void)setHelloString:(NSString*)helloString {
//This method gets called when the helloString property is assigned a value.
//Save the value in the iVar
_helloString = helloString;
//Take whatever other action that is necessary.
}
就我而言,答案不是KVO或自定义设置器。 我最终使用[NSNotificationCenter defaultCenter]
并发布了从FirstViewController
发出的通知,该通知将在SecondViewController
观察到,并且如果释放了任何通知都不会使应用程序崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.