Save local data in Swift

2015-09-02 12:14

I was working on my iOS application, Pend.la, developed in Swift and I needed to store some user-created strings on the device, but I couldn’t  seem to find a simple and quick way to store/receive the user strings on the device. So I started to look in to how to do it and it turned out to be really simple with just a few lines of code.

The simplest solution if you are just storing basic strings is to use NSUserDefaults. So with just a few lines of code, this is what I got.

let defaults = NSUserDefaults.standardUserDefaults()

// Store
defaults.setObject("theGreatestName", forKey: "username")

// Receive
if let name = defaults.stringForKey("username") {
    print(name)
    // Will output "theGreatestName"
}

So by using NSUserDefaults.standardUserDefaults() we get the defaults object that what can use .setObject( … ) and .stringForKey( … ).

And there you have it. Simple as that. However, if you’re looking to store a lot more then just simple string data I would recommend you to have a look at Core data and specifically this article by Pietro Rea


Recent blog posts


The Travel (Working title)

So as I wrote in the previous blog post, I’m working on a game. The working title for the game is now set to “The Travel” and why that is I’ll keep as a secret for now....

Read more


Defold - A game engine

Most of you probably never heard of a game engine called Defold. It’s a 2d game engine developed by King, which is made so that you...

Read more