Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to Access Application Delegate Variables / Properties

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.

like image 213
Bryan Avatar asked Jul 26 '26 19:07

Bryan


1 Answers

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.

like image 112
Rudi Avatar answered Jul 28 '26 09:07

Rudi