继承我正在使用的代码,之后看到我的错误
@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'协议
我的代码中缺少什么?
答案 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);