views:

56

answers:

3

The question title pretty much gives it away - I'd like my app to remember a few things. It's some sort of calculator, so it should save the last used values and some user selectable settings.

Basically I'd like to save a handful of floats and BOOLs and load them again the next time the app loads.

What's the best and easiest way to do that?

Thanks!!

+1  A: 

You are looking for NSUserDefaults

ennuikiller
+3  A: 

One of the easiest ways would be saving it in the NSUserDefaults:

Setting:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[userDefaults setObject:value 
                 forKey:key];
// – setBool:forKey:
// – setFloat:forKey:  
// in your case 
[userDefaults synchronize];

Getting:

[[NSUserDefaults standardUserDefaults] objectForKey:key];

– boolForKey: and – floatForKey: here in your case

Gauloises
Perfect! Thanks!
Toastor
A: 

Besides the very good NSUserDefaults approach, there is another easy way to store data from an NSArray,NSDictionary or NSData object is to use the methods:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

respectively (for a NSDictionary):

+ (id)dictionaryWithContentsOfFile:(NSString *)path

you just have to give a valid path to a location. Usually the document directory is a good place to put your app data. (see here)

In order to store/load a dictionary from a filed called "managers" in your document directoy you could use these methods:

-(void) loadDictionary {
    //get the documents directory:
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //make a file name to write the data to using the //documents directory:
    NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", documentsDirectory];
    NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName];
    if (panelLibraryContent != nil) {
        // load was successful do something with the data...
    } else {
        // error while loading the file
    }   
}

-(void) storeDictionary:(NSDictionary*) dictionaryToStore {
    //get the documents directory:
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //make a file name to write the data to using the
    //documents directory:
    NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", documentsDirectory];

    if (dictionaryToStore != nil) {
        [dictionaryToStore writeToFile:fullFileName atomically:YES];
    }
} 

Anyway this approach is very limited and you have to spend a lot of extra work if you want to store more complex data. In that case the CoreData API is very very handy.

Chris