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
2010-06-19 05:37:30
+1
A:
[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]
Devara Gudda
2010-06-19 05:37:36
+2
A:
more precisely
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:@"timestamps"];
[standardUserDefaults synchronize];
}
}
mihirpmehta
2010-06-19 05:38:06
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
2010-06-19 06:29:38
fair enough....
mihirpmehta
2010-06-19 07:22:43
+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
2010-06-19 06:04:31