views:

477

answers:

4

How to save a string into the NSUserDefaults?

+4  A: 
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults]
    setObject:valueToSave forKey:@"preferenceName"];

to get it back later

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];
drawnonward
+1  A: 

[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

Devara Gudda
+2  A: 

more precisely

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

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"timestamps"];
        [standardUserDefaults synchronize];
    }
}
mihirpmehta
There is no need to perform the nil check for `standardUserDefaults` object. It is perfectly fine to send messages to nil in Objective-C.
jbrennan
fair enough....
mihirpmehta
+3  A: 

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

v01d