Jules
Jules

Reputation: 7766

iPhone, how do usa an App Delegate variable so it can be used like global variables?

Heres the code I'm using, see my error afterwards

@interface MyAppDelegate : NSObject  {
  NSString *userName;
}
@property (nonatomic, retain) NSString *userName;
...
@end

and in the .M file for the App Delegate you would write:

@implementation MyAppDelegate
@synthesize userName;
...
@end

Then, whenever you want to fetch or write userName, you would write:

MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
someClass.someString = appDelegate.userName;  //..to fetch
appDelegate.userName = ..some NSString..;     //..to write

warning: type 'id ' does not conform to the 'MyAppDelegate' protocol

What am I missing in my code ?

Upvotes: 2

Views: 9361

Answers (2)

Ayushi H
Ayushi H

Reputation: 11

Yes, you can access any variable value by making it global.

For Example:

AppDelegate.h

{
    NSString *username;
}

@property (strong,nonatomic) NSString *username;

AppDelegate.m (in @implementation block)

@synthesize username;

AnyViewController.h

#import AppDelegate.h

AnyViewController.m

//Whatever place you want to access this field value you can use it like.

AppDelegate *appdel=(AppDelegate *)[[UIApplication sharedApplication] delegate];

NSString *unm=appdel.username;

//You can get the username value here.
NSLog(@"%@",unm);

Upvotes: 1

Guy Ephraim
Guy Ephraim

Reputation: 3520

You should add a cast to MyAppDelegate

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];

Upvotes: 13

Related Questions