xcode iPhone,如何使用 App Delegate 变量才能像全局变量一样使用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3833294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:48:03  来源:igfitidea点击:

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

iphonexcodeiphone-sdk-3.0

提问by Jules

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:

在 App Delegate 的 .M 文件中,您将编写:

@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

警告:类型“id”不符合“MyAppDelegate”协议

What am I missing in my code ?

我的代码中缺少什么?

回答by Guy Ephraim

You should add a cast to MyAppDelegate

您应该向 MyAppDelegate 添加演员表

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

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

回答by Ayushi H

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

是的,您可以通过将其设为全局来访问任何变量值。

For Example:

例如:

AppDelegate.h

AppDelegate.h

{
    NSString *username;
}

@property (strong,nonatomic) NSString *username;

AppDelegate.m(in @implementation block)

AppDelegate.m(在@implementation 块中)

@synthesize username;

AnyViewController.h

AnyViewController.h

#import AppDelegate.h

AnyViewController.m

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