iPhone – Accessing the Global Variables in the AppDelegate

Sometimes u would need to create some Global Variables in an iPhone Application such that they can be accessed in other implementation class files.

Those Global Variables are created in the AppDelegate. If you want to access it in another file, you have to get the AppDelegate instance before you can read or write the Global Variables. For example, the HelloAppDelegate has a NSString instance variable named as greeting and i want to read it in the HelloViewController.m

HelloViewController.m

// Get the HelloAppDelegate
HelloAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

// Show the greeting in the log
NSLog(appDelegate.greeting);

 

An alternate way is creating and wiring an app delegate variable in the HelloViewController with the App Delegate Object in the MainWindow.xib.

Thanks Steve for telling me about that.
Done =)

10 thoughts on “iPhone – Accessing the Global Variables in the AppDelegate”

  1. I’d spent 2 days trying to get this to work, until I came across your post.

    What I had been doing was too complex, so it’s great to find the solution was so simple.

    Many thanks

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.