Monday, April 16, 2012

Save string to the NSUserDefaults?


How to save a string into the NSUserDefaults?



Source: Tips4all

5 comments:

  1. NSString *valueToSave = @"someValue";
    [[NSUserDefaults standardUserDefaults]
    setObject:valueToSave forKey:@"preferenceName"];


    to get it back later

    NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

    ReplyDelete
  2. more precisely

    -(void)saveToUserDefaults:(NSString*)myString
    {
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
    [standardUserDefaults setObject:myString forKey:@"timestamps"];
    [standardUserDefaults synchronize];
    }
    }

    ReplyDelete
  3. Something like this:

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    // saving an NSString
    [prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];


    Then to retrieve:

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    // getting an NSString
    NSString *myString = [prefs stringForKey:@"keyToLookupString"];


    You should really check out Apple's NSUserDefaults Class Reference and also maybe this tutorial: iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

    ReplyDelete
  4. [[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

    ReplyDelete
  5. I would like to ask if there is any possibility to save image same way??? and if I can save more images this way???

    like [[NSUserDefaults standardUserDefaults] setValue:myImage1 forKey:@"1"]
    [[NSUserDefaults standardUserDefaults] setValue:myImage2 forKey:@"2"] and so on...... and save it on app quitting .....and when starting again load it like this .......

    UIImage *myImage1 = [[NSUserDefaults standardUserDefaults] imageForKey:@"1"];

    is it possible?????

    ReplyDelete