Search code examples
swiftyuserdefaults

Swfit - How can I use the UserDefaults to store variable and how to load the variable from UserDefaults next time


I need to store some variables like ione and itwo which for method repeat. The variables value will increase,after increased,I want to store the increased variables into userdefaults.

    import UIKit

    class ViewController: UIViewController 
{

    override func viewDidLoad() 
    {
    super.viewDidLoad()
/* How can I  load UserDefaults here to restore ione's value and 
           itwo's value and How to store them in UserDefaults ? */

let ionevalue = ione
println(ionevalue)

let itwovalue = itwo
println(itwovalue)

    // Do any additional setup after loading the view, typically from a nib.
     }

 var ione = 0
 var itwo = 0
 ione++
 itwo++ 

 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
     }
}

Solution

  • ok,I finally got inspired in SOF and I figure it out,I initial a public NSUserDefaults can be used in any Func:

     let  aaa = NSUserDefaults.standardUserDefaults()
    

    and use below code to store the update value :

      aaa.setObject(AnythingYouInitialed, forKey: "DefineAKeyYouWant")
    

    and use below code to load the value from NSUserDefaults:

     if let bbb = aaa.valueForKey("DefineAKeyYouWant") as?Int
        {
            ccc = bbb
    
        }
    

    Now I have load the value and I can use it by assign ccc into other variabels.

    I'm a old guy of 30 years old and I'm just starting be a programmer,that's not easy for me...haha...