iPhone,怎么做一个App Delegate变量,所以它可以像全局变量一样使用?

时间:2010-09-30 17:42:11

标签: iphone xcode iphone-sdk-3.0

继承我正在使用的代码,之后看到我的错误

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

并在App Delegate的.M文件中写下:

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

然后,每当您想要获取或写入userName时,您都会写:

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

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

我的代码中缺少什么?

2 个答案:

答案 0 :(得分:13)

您应该向MyAppDelegate添加强制转换

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

答案 1 :(得分:1)

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

例如:

<强> AppDelegate.h

{
    NSString *username;
}

@property (strong,nonatomic) NSString *username;

AppDelegate.m (在@implementation块中)

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