Reputation: 17581
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.
Upvotes: 3
Views: 7063
Reputation: 36752
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).
Upvotes: 2
Reputation: 2460
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.
Upvotes: 8