1

I have a super simple app idea that I'm building out in order to get more practices at using Swift. I just want to ask if using NSUserDefaults is the most appropriate choice. All I will have is list of names with a number associated with each name that I will update (the number) from time to time. I was going to use a NSDictionary for the data.

I think Core Data is over kill for something like this.

I just wanted to get a 2nd opinion on my idea on how to save the data for this simple app.

Thanks

icekomo
  • 9,328
  • 7
  • 31
  • 59

2 Answers2

1

You can use NSUserDefault. But If want to store an array or dictionary you have to do some extra work. The documentation says:

The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects.

You can convert your NSDictionary to NSData, then save it to NSUserDefault.

// Convert the dictionary and store
var data = NSKeyedArchiver.archivedDataWithRootObject(yourDict)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: yourKey)

// Retrieving the dictionary
var savedData = NSUserDefaults.standardUserDefaults().dataForKey(yourKey)
var dict = NSKeyedUnarchiver.unarchiveObjectWithData(savedData)

Hope this helps.. :)

Rashad
  • 11,057
  • 4
  • 45
  • 73
  • 2
    There's no need to convert anything. NSDictionary is fine with a key-value pair that are both NSStrings. – Wyetro Aug 25 '14 at 04:40
0

If it's just one NSDictionary that should be fine. NSUserDefaults is good for small things like that.

NSUserDefaults.standardUserDefaults().setObject(**YOUR DICTIONARY**, forKey: **YOUR KEY**)
Wyetro
  • 8,439
  • 9
  • 46
  • 64