Save string to the NSUserDefaults?


How to save a string into the NSUserDefaults?


For saving use this :

[[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"KTerminated"];
[[NSUserDefaults standardUserDefaults]synchronize];

For Retriveing use this :

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];
By : Subbu

-(void)saveToUserDefaults:(NSString*)string_to_store keys:(NSString *)key_for_the_String
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:string_to_store forKey:key_for_the_String];
        [standardUserDefaults synchronize];

And call it by:

[self saveToUserDefaults:@"string_to_store" : @"key_for_the_string"];

Retrieve the string by using:

NSString * stored_string = [[NSUserDefaults standardUserDefaults] stringforkey:key_for_the_String]

Here For Swift i create two function which call for save and retrive value for key from Preference

may be this is help full for u

// for saving object

static func setObject(value:AnyObject ,key:String)
    let pref = NSUserDefaults.standardUserDefaults()
    pref.setObject(value, forKey: key)

static func getObject(key:String) -> AnyObject
    let pref = NSUserDefaults.standardUserDefaults()
    return pref.objectForKey(key)!

This video can help you solving your question :)
By: admin