开发者

What is an effective way to hold a universal constant on an iphone app?

I'm trying to create an iPhone app in which I connect to an API and get a security string and id with which to make requests to the api.

The string and id change every time the app is run, and multiple view controllers in the application need 开发者_如何学Pythonthe information.

How can I effectively store that information so it can be easily accessed by various classes?

Thanks in advance! AJ


Using the app delegate seems to be the "old school" way of doing it, but I think it's a lousy habit to get into. You turn your app delegate into a giant global variable, which is never a Good Thing.

Storing in NSUserDefaults works, although if it's not really a setting you want to save (and you might not given your security considerations), this can come back to haunt you later.

I'm hardcore: I'd instantiate a data model class in your app delegate to hold information like this, and pass it along to your root view controller and onward to any other view controllers that need access to the information. Advantages? No global variables, nothing gets persisted to user defaults, and only those parts of your code that really need the information ever see it (reduces Action At A Distance). Disadvantages? Not as easy to set up as the other two methods (at least the first time).


As you can imagine there are lots of ways, here is one using NSUserDefaults:

Storing:

[[NSUserDefaults standardDefaults]setObject:@"some string" forKey:@"key"];

Retrieving:

NSString *key = [[NSUserDefaults standardDefaults]objectForKey:@"key"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜