tags:

views:

1127

answers:

2

I have been making a few apps here and there, and I know my way around. What has always confused me is accessing global attributes, and where the best place to set them are. I have a few questions about accessing things and how to access them.

Do you have to include your application delegates header file into any other other file you want to access it in? Say I have a view controller, that I would like to use, do I need to include the .h inside my view controller's .h? Or can I set the:

@class AppDelegate;

Can you only access the delegate by typing out:

[UIApplication sharedApplication].delegate

EACH and every time? Is that something I just have to get used to? Or could I set the following in my implementation in each .h:

AppDelegate *delegate;

And inside the init function, put the singleton instance to that variable?

Sorry if this was off structure, but I think it's a logical question people have a problem encountering and solving.

+4  A: 

Maybe you need to reconsider how you are using the App Delegate? It sounds to me like perhaps you are not making a very good class design.

Regardless, here's a way to make it easy. Don't put this in init just use it when you need it.

MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

Naturally, replace MyAppDelegate with the actual class name of your app delegate.

John Fricker
And to not repeat yourself, you might put that code in a class method in your delegate like so: + (MyAppDelegate*)applicationDelegate { return (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; }
Peter DeWeese
A: 

Another possibility is to add the code to use a properly casted app delegate reference as a #define in the app delegate header file, so after including it you can do something like:

MYAPPDELEGATE.customProperty = blah;

However I tend to favor just writing out the line that John presented, as use of #defines confuses code completion which I find more annoying than just typing the line.

As also mentioned, if you have a ton of references to the app delegate you may want to restructure to keep some of those references closer to home.

Kendall Helmstetter Gelner