如何在所有 类 中拥有一个 NSString 值?
how to have a NSString value in all classes?
我需要在 viewController 中捕获数据并在应用程序执行期间保持存储状态,您可以在我拥有的任何其他视图中使用它,尝试在 AppDelegate 中创建一个 NSString,如下所示:
AppDelegate.h
property (Retain, nonatomic) NSString * token;
AppDelegate.m
synthesize token;
然后在另一个class中调用如下
添加包含
#include "AppDelegate"
创建对象
AppDelegate * theToken = [[AppDelegate allow] init];
label.text = theToken.token;
但对我不起作用,在某些 ViewController 中出现 nill
问题是您正在创建 AppDelegate 的全新实例,而不是访问当前实例。
而不是:
AppDelegate * theToken = [[AppDelegate alloc] init];
试试这个:
AppDelegate * theToken = (AppDelegate*)[[UIApplication sharedApplication] delegate];
编辑:正如 rmaddy 和 Louis Tur 在评论中也指出的那样,您对 retain 和 synthesize 的使用是 ARC 之前的遗物。
"Strong" 是 "retain" 的 ARC 等价物,因此您可以将 属性 更新为以下内容以保持强引用:
property (strong, nonatomic) NSString * token;
此外,曾几何时(直到某个时间 post-ARC,但如果我没记错的话,在 iOS6 之前),需要在 .m 中合成 .h 属性。但在现代时代,在 .m 中省略 synthesize
并使用 "self" 访问 AppDelegate.m
中的 属性 通常是一种很好的做法;例如,self.token
.
我需要在 viewController 中捕获数据并在应用程序执行期间保持存储状态,您可以在我拥有的任何其他视图中使用它,尝试在 AppDelegate 中创建一个 NSString,如下所示:
AppDelegate.h
property (Retain, nonatomic) NSString * token;
AppDelegate.m
synthesize token;
然后在另一个class中调用如下
添加包含
#include "AppDelegate"
创建对象
AppDelegate * theToken = [[AppDelegate allow] init];
label.text = theToken.token;
但对我不起作用,在某些 ViewController 中出现 nill
问题是您正在创建 AppDelegate 的全新实例,而不是访问当前实例。
而不是:
AppDelegate * theToken = [[AppDelegate alloc] init];
试试这个:
AppDelegate * theToken = (AppDelegate*)[[UIApplication sharedApplication] delegate];
编辑:正如 rmaddy 和 Louis Tur 在评论中也指出的那样,您对 retain 和 synthesize 的使用是 ARC 之前的遗物。
"Strong" 是 "retain" 的 ARC 等价物,因此您可以将 属性 更新为以下内容以保持强引用:
property (strong, nonatomic) NSString * token;
此外,曾几何时(直到某个时间 post-ARC,但如果我没记错的话,在 iOS6 之前),需要在 .m 中合成 .h 属性。但在现代时代,在 .m 中省略 synthesize
并使用 "self" 访问 AppDelegate.m
中的 属性 通常是一种很好的做法;例如,self.token
.