在 MyViewController.h 中声明:
AppDelegate *appDelegate;
@property (nonatomic, strong) AppDelegate *appDelegate;
在MyViewController.m的viewDidLoad中:
self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
localAppDelegate= (AppDelegate *)[[UIApplication sharedApplication] delegate];
出于某种原因,appDelegate 保持为空,但 localAppDelegate 已正确分配。
为什么没有正确分配 self.appDelegate?
最佳答案
嗯,根据你的评论,Erik localAppDelegate 应该始终可以访问,但一定要将 AppDelegate header 导入到你想在其中使用 appDelegate 的类中......如果你需要存储变量,如用户设置,公共(public)变量......等.我更喜欢使用 NSUserDefaults
它很简单,建议在这种情况下使用。这是一个简单的示例,用于从 NSUserDefaults
中保存和获取字符串。
设置:
NSString *str = @"Malek";<br/> [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"myName"]; [[NSUserDefaults standardUserDefaults] synchronize];
2.获取:
NSString *myName = [[NSUserDefaults standardUserDefaults] valueForKey:@"myName"];
关于ios - 如何将应用程序委托(delegate)引用分配给 viewDidLoad 中的 View Controller 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222066/