安装在NSString iOS中
嗨,我是新的IOS开发,我想从委托类和从其他类访问设置nsstring的值,我得到的价值是null.i不知道我在做什么错误?
//token class header file @interface TokenClass : NSObject { NSString *tokenValue; } @property (nonatomic,strong) NSString *tokenValue; //token class main file @implementation TokenClass @synthesize tokenValue; @end //App Delegate TokenClass *token = [[TokenClass alloc]init]; [token setTokenValue:@"as"];
当我访问一些其他类中的tokenvalue我得到空值。 可以任何一个点我什么错误,我在做什么?我正确使用@属性?
您需要使用Singleton类将variables或对象展示给整个项目或创build全局variables。 创buildTokenClass类的sharedInstance并创build可以在任何地方访问的属性
在你的.h
文件中
//token class header file @interface TokenClass : NSObject @property (nonatomic,strong) NSString *tokenValue; //create static method + (id)sharedInstance;
在.m
文件中
#import "TokenClass.h" @implementation TokenClass #pragma mark Singleton Methods + (id)sharedInstance { static TokenClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } - (id)init { if (self = [super init]) { tokenValue = [[NSString alloc] init]; } return self; } @end
现在在你的appDelegate
#import TokenClass.h @implementation AppDelegate in `didFinishLaunchingWithOptions:` [TokenClass sharedInstance] setTokenValue:@"as"];
在任何课堂上,你都可以使用它
NSLog(@"tokenValue = %@", [[SingletonClass sharedInstance] tokenValue]);
有很多方法可以实现你想要的:
1.通常我使用NSUserDefaults
来保存less量的数据,即使用户closures了应用程序,我也需要这些数据。 有很多信息如何使用它。 在这里看到我的答案 。
2.在你的UIViewController类(例如你的rootViewController)中创build@property,它将保存你的TokenClass
。 然后你会通过tokenValue
得到self.tokenClass.tokenValue
3.另一种方法是创build一个单例类,在应用程序的整个运行循环中都可以使用它。 辛格尔顿候选人必须满足三个要求:
- 控制对共享资源的并发访问。
- 将从系统的多个不同部分请求访问资源。
-
只能有一个对象。
+(TokenClass*) sharedTokenClass {
static dispatch_once_t pred; static TokenClass *_sharedTokenClass = nil; dispatch_once(&pred, ^{ _sharedTokenClass = [[TokenClass alloc] init]; }); return _sharedTokenClass; }
您将从
[TokenClass sharedTokenClass]tokenValue];
任何地方使用它[TokenClass sharedTokenClass]tokenValue];
如果我是你,我会使用第一个变体。
PS。 我强烈build议你阅读一些内存pipe理文章,以获得对象的生命周期点。