hi i am new to ios dev ,I am trying to set a value for nsstring from delegate class and access from other class ,the value i get is null.i dont know what mistake i am doing?
//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"];
when i access tokenvalue in some other classs i get null value. can any one point me what mistake i am doing?Am i using @ property correctly?
There are a lot of ways to achieve what you want:
1. Usually I am using
NSUserDefaults
to save small amount of data which I will need even the user closed the app. There are a lot of information how to use it. See my answer here.2. In your UIViewController class (e.x. your rootViewController) create
@property
which will hold yourTokenClass
. Then you will gettokenValue
byself.tokenClass.tokenValue
3. The other way is create a singleton class which will be available during the whole run loop of your application. A Singleton candidate must satisfy three requirements:
there can be only one object.
+(TokenClass*) sharedTokenClass {
You will use it it from any place you want by
[TokenClass sharedTokenClass]tokenValue];
If I were you, I would use the first variant.
PS. I strongly recommend you to read some memory management articles to get the point of object's lifecycle.
You need to use Singleton class to expose variables or objects to the entire project or create global variables. Create sharedInstance of TokenClass class and create property which can be accessed anywhere
in your
.h
filein
.m
filenow in your appDelegate
in any class you can get value using