我需要在viewController中捕获数据并在应用程序执行期间保存,您可以在我拥有的任何其他View中使用它,尝试在AppDelegate中创建NSString,如下所示:
AppDelegate.h
property (Retain, nonatomic) NSString * token;
AppDelegate.m
synthesize token;
然后在另一个类中调用它,如下所示
添加include
#include "AppDelegate"
创建对象
AppDelegate * theToken = [[AppDelegate allow] init];
label.text = theToken.token;
但没有工作,在一些ViewController中出现nill
答案 0 :(得分:7)
问题是你正在创建一个全新的AppDelegate实例,而不是访问当前的实例。
而不是:
AppDelegate * theToken = [[AppDelegate alloc] init];
试试这个:
AppDelegate * theToken = (AppDelegate*)[[UIApplication sharedApplication] delegate];
编辑:正如rmaddy和Louis Tur在评论中指出的那样,你使用保留和合成是ARC之前的遗物。
“强”是ARC的等同于“保留”,因此您可以将您的属性更新为以下内容以保持强大的参考:
property (strong, nonatomic) NSString * token;
此外,曾几何时(直到ARC之后的某个时间,但如果我没记错的话,还是iOS6之前的版本),需要在.m中合成.h属性。但在现代,通常优良做法是在你的.m中省略synthesize
,而是使用“self”访问AppDelegate.m
内的属性;例如,self.token
。