views:

386

answers:

2

I am using a variable/propery of my application delegate as a global. (I don't want to deal with a singleton class.)

I am trying to write a #define statement in my Application Delegate class. If I type:

  [UIApplication sharedApplication]

in my app delegate class, code hinting does not recognize sharedApplication. But if I type the same thing in a viewController class, "sharedApplication" pops right up.

In order to define a NSMutableDictionary in my applicationDelegate.h (or .m?), I write:

#define MyDictionary [[[UIApplication sharedApplication] delegate] stateDictionary]

Then if I try to use it in another class:

[[MyDictionary objectForKey:@"California"] largestCity];

I get an error that MyDictionary must be declared first. I am really confused about a lot of concepts here.

+2  A: 

I'm pretty sure that someone will answer this better, but here's a quick one:

Let's say your application is called myApplication. Assign "global" property to MyApplicationDelegate, and then it will be accessible from anywhere like this:

// get reference to app delegate
MyApplicationDelegate *appDelegate = (MyApplicationDelegate *)[[UIApplication sharedApplication] delegate]

Property *myProperty = appDelegate.property;

Also, make sure that you link to MyApplicationDelegate file in header:

#import "MyApplicationDelegate.h"

There's a longer debate if using "global" objects is good design in general, but I won't go into that now.

Rudi
That works great. Thank you. Is there anyway to define it so I can access the variable without using your 2 statements? Do I have to release them? If I did release them would they it release my AppDelegates instance of the dictionary and delegate?
Bryan
Also, in the first part of my question, what is the difference between the two appDelegates?
Bryan
You do have to use those two lines, unfortunately. There are no real global variables that I know of, but then again I don't use them in my code. :)Releasing: release them in class where you created them. If you created them in MyApplicationDelegate, for example, release them in dealloc method there.App delegate question: start a new stackoverflow question. :) It's a topic of it's own...
Rudi
A: 

I always add a category to UIApplication such as this:

@interface UIApplication (MyAppDelegate)
+(MyAppDelegate*)sharedMyAppDelegate;
@end

This way I do not have to worry about type casts at all. I often define and implement this category in the same file as the MyAppDelegate class itself. So this is the header I #import all over. All you can add it to your MyProject_Prefix.chp file.

Singletons are not bad, if your architecture is properly layered (And yes it is fully testable).

PeyloW