开发者

Using two delegates

I am new to iPhone programming. I want to call a function which belongs to one of my views in MyA开发者_运维问答ppDelegate. I want to do this because I cannot find any ApplicationDidEnterBackground() event in view. So, basically I want to call view's function when the application is minimized. I did try using delegate. However I cannot find how to use two delegates as MyAppDelegate already has one. Please help.


The general design pattern is, if you have multiple interested parties in an event, don't use delegates but notifications. In this case, you should register a UIApplicationDidEnterBackgroundNotification in your -init method of every class where you wanna handle the event:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(didEnterBackground)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:[UIApplication sharedApplication]];

Then write a -(void)didEnterBackground method with your code. In your -dealloc method, make sure to unregister the notification:

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:UIApplicationDidEnterBackgroundNotification
                                              object:nil];

Also, be aware that this code requires iOS 4.x or higher. If you want to maintain iOS 3 compatibility you've to check the availability first:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(applicationState)]) {
    // register UIApplicationDidEnterBackgroundNotification
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜