Persistent Data Storage with NSUserDefaults in Swift

If you need to store data between restarts of your iOS apps or occasions like that, then you probably need to use NSUserDefaults. Below you may see how to store data with NSUserDefaults. And as far as i understand, concept is named as Persistent Data Storage.

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // creating variables and initializing -> setObject(variable_value, variable_name)
        NSUserDefaults.standardUserDefaults().setObject("Timur", forKey: "name")
        NSUserDefaults.standardUserDefaults().setObject("Yildirim", forKey: "surname")
        NSUserDefaults.standardUserDefaults().setInteger(24, forKey: "age")
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isOnline")
        NSUserDefaults.standardUserDefaults().setFloat(3.14159, forKey: "pi")
        NSUserDefaults.standardUserDefaults().setDouble(2.71828, forKey: "euler")
        
        let blog = NSURL(string: "https://timuraykutyildirim.wordpress.com/");
        NSUserDefaults.standardUserDefaults().setURL(blog!, forKey: "myBlog")
        
        
        // sync initialized data into iOS
        NSUserDefaults.standardUserDefaults().synchronize()
        
        /* The exclamation mark at the end of this statement,
           if we would not have that, our output would be (Optional 24)
           so with ” ! ” we are telling xcode that the value does exist indeed. */
        println(NSUserDefaults.standardUserDefaults().objectForKey("age")!)
    }

Testing

Suppose you don’t have any iOS device when you want to test this code.  This is how you should do it:

  1. First, run the code as it is.
  2. Click “Stop Running” button on your Xcode
  3. Close your simulator (CMD+Q)
  4. Comment-in the decleration of your variable. In my case, it’s the line with  << setInteger(24, forKey: “age”) >>
  5. Run your application again. It’ll still print variable.
  6. Click “Stop Running” button on your Xcode
  7. Click (iOS Simulator) >> (Reset Content and Settings…) in your simulator’s File menu
  8. Close again your simulator (CMD+Q)
  9. Run your application one more time and this time it won’t work as it shouldn’t have in the first place.

Yorum bırakın

Filed under Swift

Bir Cevap Yazın

Aşağıya bilgilerinizi girin veya oturum açmak için bir simgeye tıklayın:

WordPress.com Logosu

WordPress.com hesabınızı kullanarak yorum yapıyorsunuz. Log Out / Değiştir )

Twitter resmi

Twitter hesabınızı kullanarak yorum yapıyorsunuz. Log Out / Değiştir )

Facebook fotoğrafı

Facebook hesabınızı kullanarak yorum yapıyorsunuz. Log Out / Değiştir )

Google+ fotoğrafı

Google+ hesabınızı kullanarak yorum yapıyorsunuz. Log Out / Değiştir )

Connecting to %s