Ravi Kumar Singh
Ravi Kumar Singh

Reputation: 187

Using two delegates

I am new to iPhone programming. I want to call a function which belongs to one of my views in MyAppDelegate. 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.

Upvotes: 1

Views: 520

Answers (1)

Ortwin Gentz
Ortwin Gentz

Reputation: 54141

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
}

Upvotes: 3

Related Questions