Search code examples
iphonexcodeiphone-sdk-3.0

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 ?


Solution

  • You should add a cast to MyAppDelegate

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