开发者

How to call a method/selector when a variable/object changes value on iPhone

开发者 https://www.devze.com 2023-01-16 21:17 出处:网络
I\'m looking for a way to \"monitor/observe\" a singleton class I\'m using to pass information back from an asynchronous http request. I want to update the UI once I have received and parsed the respo

I'm looking for a way to "monitor/observe" a singleton class I'm using to pass information back from an asynchronous http request. I want to update the UI once I have received and parsed the response. Since iPhone SDK does not have an NSArrayController to monitor my data in the singleton, how can I do an asynchronous开发者_StackOverflow UI update?

This is how I have my logic separated:

Singleton: (hold's array with data)

RESTClient: retrieves xml from a remote service and saves to array in singleton

ViewController: need to monitor for changes to singleton's data and update UI via a function

Thank you in advance :)


While iOS does not have NSArrayController, it does have all the techniques this is build on top. Specifically, this is Key-Value-Binding and more fundamental Key-Value-Observation. The latter should be your tool of choice. It's pretty easy to do:

1) Register your controller as an observer, like that:

[singleton addObserver:self forKeyPath:@"myData" options:0 context:@"data"];

2) Observe all changes as they come in:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == @"data") {
        // Do whatever you need to do...
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
0

上一篇:

:下一篇

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号