2

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 ?

2 Answers 2

13

You should add a cast to MyAppDelegate

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

5
  • 4
    This is the answer--cast to your type of App Delegate as you pull the reference from UIApplication. That said, if you have many of those sorts of data fields, you should consider housing them in a data manager singleton. Keeping all your data as properties of your application delegate isn't a fantastic approach.
    – Dan Ray
    Commented Sep 30, 2010 at 17:57
  • Dan, I agree, it is not the best practice to the the AppDelegate for these kind of hostings. Commented Sep 30, 2010 at 18:02
  • I'm using an NSNumber as well as a NSString and I'm getting error, see below my code.
    – Jules
    Commented Sep 30, 2010 at 18:11
  • You should do intValue and not integerValue Commented Sep 30, 2010 at 18:12
  • This should probably be asked as a separate question, as I can't type a well formatted answer in a comment. Basically, arrays only store objects, not primitive types, so your passing an object to numberWithInt: when it expects an integer. Commented Sep 30, 2010 at 18:16
1

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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.