I have to save a token that I receive from an API (HTTP basic authentication). The token will be transmitted for every request on the application (in every classes). The App receive that token in the first class and should not ask again a new token!
How could I开发者_如何转开发 make to save the token???
Class1 : ask a token, use the token during requests Class2 : use the token during requests
Thanks from an iPhone newbie ;-)
You could create a singleton object that is used to store the token in. Class1 would get the token and would then give this token to the singleton. The singleton would then hold this token and make it available to all other classes as and when they need it.
Class1:
myToken = [self getToken];
[TokenStoringSingleton setToken:myToken];
....
Class2 (or any other class that wants to use the token):
myToken = [TokenStoringSingleton getToken];
....
You could also create a new instance variable in your App Delegate to store it e.g. MyAppDelegate.h
NSString *myToken;
@property (nonatomic, retain) NSString *myToken;
MyAppDelegate.m
@synthesize myToken;
Then you could use it from your classes Class1:
myToken = [self getToken]; // This calls a method that gets the token from the server
MyAppDelegate *delegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
delegate.myToken = myToken;
Class2:
MyAppDelegate *delegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
myToken = delegate.myToken;
精彩评论