Sabha B
Sabha B

Reputation: 2089

Iphone access a property value from AppDelegate

How to access a property value of AppDelegate class from someView Controller without creating reference of the delegate in view controller?

Upvotes: 25

Views: 19680

Answers (3)

madmik3
madmik3

Reputation: 6983

[UIApplication sharedApplication].delegate;

Upvotes: 2

Tim
Tim

Reputation: 60150

I'm not quite sure what you mean - there are multiple ways to get information from your application delegate into a view controller, and the phrase "without creating reference of the delegate" is unclear. Your options basically are:

  1. Reference the application delegate, casting as appropriate. You would write code in your view controller class like:
    id propertyValue = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] myProperty];
  2. Pass the property in when creating the view controller. This requires the view controller to have a @property declared and @synthesized for use, then you would have the app delegate just set the property on the view controller instance.

Neither of these options require that you retain a copy of your app's delegate as a @property, but the first does reference the delegate once.

Upvotes: 52

par
par

Reputation: 17734

[UIApplication sharedApplication].delegate

You'll also need to include the app delegate header file in your view controller and possibly typecast the delegate from id to your actual app delegate class.

#include "MyAppDelegate.h"

((MyAppDelegate *)[UIApplication sharedApplication].delegate).myProperty;

Upvotes: 20

Related Questions