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

痴心易碎 提交于 2019-12-10 11:06:28

问题


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 ?


回答1:


You should add a cast to MyAppDelegate

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




回答2:


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


来源:https://stackoverflow.com/questions/3833294/iphone-how-do-usa-an-app-delegate-variable-so-it-can-be-used-like-global-variab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!