简体   繁体   中英

Creating global variables in Objective C

I have designed a login app. I have entered the account data in sqlite database. However when I logged in with the account username and password i want these to be accessible to all view controllers. Because, I have different controllers which will update the account details. Need implementation details.. Thanks

Use a singleton: http://www.galloway.me.uk/tutorials/singleton-classes/

I have a project with something like this (note I'm using the iOS keychain rather than a database, but I've hidden those details here):

@interface User : NSObject
@property (nonatomic, strong) NSString *username;

+ (User *)currentUser;

@end

@implementation User

+ (User *)currentUser
{
    static User *currentUser = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        currentUser = [[User alloc] initFromKeychain];
    });
    return currentUser;
}
@end

There are A LOT of approaches to doing singletons (depending on how paranoid you want to be about whether someone can create a non-singleton instance of your class or not). Examples here: What should my Objective-C singleton look like?

You could also just access the keychain directly wherever you need it. You should also ask yourself why so much of your code needs access to a username/password. Sounds like a broken design.

Avoid global variables, rather you can use a Singleton class to store application wide credentials information.

However keep in mind that the best way to store credentials in an app is using Apple Keychain, you can find the API reference on the Apple site.

As it was said - avoid global variables, but if you want them for sure - do it like in c language:

define this variable in one file

in all other files refer to it with extern keyword

Simply: Don't do it!

I recommend to store the credentials in the keychain. But don't use the sample code Apple provides. It doesn't work. I use SSKeychain in my projects.

If you don't need to store the credentials you should, as aleroot suggested, use a singleton or a class with only one instance.

Three answers:

  • Don't do it.
  • If you must do it, use a Singleton.
  • For extremely easy access to username and non confidential (ie, password) variables, use NSUserDefaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM