NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];
to get it back later
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:@"preferenceName"];
more precisely
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:@"timestamps"];
[standardUserDefaults synchronize];
}
}
Here's how to do the same with Swift;
var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")
To get it back later;
if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
// Do something with savedValue
}
In Swift 3.0
var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")
if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {
}
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
Do not forget this statement because otherwise it may not always work:
[standardUserDefaults synchronize];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With