views:

34

answers:

2

Hey,

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 the information.

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

Thanks in advance! AJ

A: 

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"];
christo16
It doesn't need to be preserved across launches, so that's a bit unnecessary (though I think you can configure an in-memory defaults domain).
tc.
A: 

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).

Shaggy Frog