开发者

Using a singleton to post notifications to specific objects

I created a singleton class to store a reference to CLLocationManager so my entire program is accessing the same object and acts as the delegate.

I'm using a TabBarController, and several of my ViewControllers are interested in location data, as well as any errors that are generated.

Right now I'm just trying to handle the different error scenarios, and the way I have things set up is that locationManager:didFail:withError: posts a notification containing the error object. Any ViewController interested in that notification registers with NSNotificationCenter, and handles the error accordingly.

The problem I'm having is that all registered ViewControllers are receiving this error notification, even when they're not loaded by the currently selected tab. While I'm sure this is by design, is there a way to only post to the active ViewController?

Because my sender is a singleton, I can't differentiate by Notification Name or Notifica开发者_JAVA技巧tion sender since they'll always be the same.

Thanks!


While I'm sure this is by design, is there a way to only post to the active ViewController?

Sure - the simplest way is to just to put your addObserver and removeObserver methods for each view controller into the viewWillAppear and viewWillDisappear methods (or didAppear/ didDisappear).

That way, only view controllers that are actively visible will receive your notifications (I assume currently you're putting your addObserver/removeObserver methods in viewDidLoad/Unload, hence why they're getting notifications when they're not visible but still loaded).


If you want only the currently visible UIViewController to handle a particular notification, you can do this:

- (void) viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(handleFooNotification:)
                                                 name:@"FooNotification"
                                               object:nil];

}

- (void) viewWillDisappear:(BOOL)animated
{
    // remove all notifications
    //
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


I suspect the simplest suggestion is for the interested view controllers to add an observer within their viewWillAppear method and then remove the observer when viewWillDisappear is called.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜