2010-09-30 26 views
2

继承人我用,看我的错误代码后iPhone,我们如何做一个App Delegate变量,这样它可以像全局变量一样使用?

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

,并为App委托.m文件你可以这样写:

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

然后,每当你想获取或写用户名,你可以这样写:

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

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

我在代码中丢失了什么?

回答

13

您应该添加投地MyAppDelegate

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

+0

添加的代码片断 – 2010-09-30 17:56:10

+4

这就是答案 - 投放到您的应用程序类型的代表,你拉从UIApplication的参考。也就是说,如果你有很多这样的数据字段,你应该考虑把它们放在一个数据管理器单例中。将所有数据保存为应用程序委托的属性并不是一个好方法。 – 2010-09-30 17:57:25

+0

丹,我同意,这不是对这些类型的托管AppDelegate的最佳做法。 – 2010-09-30 18:02:39

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); 
相关问题