2010-09-30 87 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); 
相關問題