How would I save and load a UITextField?

前端 未结 3 543
死守一世寂寞
死守一世寂寞 2021-01-26 10:04

I have searched everywhere and tried lots of code but nothing seems to be working for me. All I need to do is to load (on viewDidLoad) a text field and save it when a button is

3条回答
  •  面向向阳花
    2021-01-26 10:51

    Use the NSUserDefaults class which was specifically made for this scenario.

    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    
    // saving a NSString (you usually do this when the value is being submitted)
    [defs setObject:textField.text forKey:@"aKey"];
    [defs synchronize]; //this commits the new value - shouldn't be necessary because this is doe automatically, but just in case...
    
    // loading a NSString (you usually do this on viewDidLoad)
    testField.text = [defs objectForKey:@"aKey"];
    

    The value is stored across sessions.
    You can store other value types as well (other than NSString).
    Use a different key for each field for which you want to store values.
    This can also be used to store app configurations/options/etc

提交回复
热议问题