tags:

views:

3969

answers:

3

I have an AppDelegate which has 3 views. I add all three

[window addSubview:gameViewController.view]; [window addSubview:viewSettings.view]; [window addSubview:viewController.view]; [window makeKeyAndVisible];

In the app delegate, i have some methodes for swapping views by calling [window bringSubviewToFront:gameViewController.view];

When i am inside viewController, I use
pinkAppDelegate *appDelegate= (pinkAppDelegate *)[[UIApplication sharedApplication] delegate];

[appDelegate switchToSettings];

to switch my subviews...so far so good.

BUT, when I'm in my viewSetting UIViewController, and do the same appDelegate call, it chocks, like it doesn't understand how to call the appDelegate method.

I've got all my views hooked in my mainwindow xib, but can't figure out why i can't traverse the methods in the main appdelegate

+5  A: 

Inside viewController, you're setting up a local variable called appDelegate that points at your app delegate. That's what this line does:

pinkAppDelegate *appDelegate= (pinkAppDelegate *)[[UIApplication sharedApplication] delegate];

This variable is local to viewController, so you can't use it in the settings view controller. You need to set up another variable there.

Alternatively, use this nice #define throughout your app. (You'll need to put it in a .h file that you include in every file in your project.)

#define myAppDelegate [[UIApplication sharedApplicaion delegate]

Then you can do the following anywhere:

[myAppDelegate doSomething];
Jane Sales
Why not call directly?:[[[UIApplication sharedApplicaion delegate] doSomething]
stefanB
Apart from the fact that UIApplication will not have those custom methods anyway ...
stefanB
@stefanB all that [[UIApplication delegate shared blah blah is ugly and this solution helps avoif errors like jalo has.
Roger Nolan
What custom methods? I'm just suggesting a #define to make the app delegate call prettier and minimise typing errors.
Jane Sales
The #define version does not seem to work for me.I get warning "UIApplication may not respond to +sharedApplication" kind of error, and is not working after launch... any suggestions?Thanks
Sasho
A: 

Jane's Answer had a Typo in it. Use the following line in a header file (e.g. defines.h) that you import in every class:

#define myAppDelegate [[UIApplication sharedApplicaion] delegate]

then in any method you can use any of the following:

[myAppDelegate doSomething]; 
 myAppDelegate.property=value;
 myAppDelegate.childClassOfMyAppDelegate.property=value;
[myAppDelegate.ChildOfMyAppDelegate doSomething]; 
Cassie
A: 

For reference there is still a typo in the above, also I have another addition which helps avoid warnings of having to cast every time. if you use:

#import "MyAppDelegate.h"
#define myAppDelegate (MyAppDelegate *) [[UIApplication sharedApplication] delegate]

I put the above in a constants.h and then can use

[myAppDelegate doSomething];

anywhere I import constants.h

agough