0

Was wondering how to use NSUserDefaults if this would be the correct solution to save data that I have in an application. The data is not very much so I though this could be a good solution. Currently stores data into objects in the app, then the objects are loaded into the array once the user sets them.

var placesChosen: [Place] = []
var myplaces: Place = Place()

class Place {
   var name: String?
   var locationAddress: String?
   var locationPhoneNumber: String?
}

function createPlace(){
   // code to add place
   placeChosen.append("some data to add")

}

I later would like to pull from the data that is stored by NSUserDefaults and show the data back to the user. Additionally I though I should mention that the user would only be able to set for objects into the array.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
randomorb2110
  • 259
  • 1
  • 4
  • 9
  • 1
    You can do this, but your `Place` class will need to adopt `NSCoding` – Paulw11 Jul 14 '16 at 04:10
  • 1
    Don't store data in `NSUserDefaults`. Write the data to a file. – rmaddy Jul 14 '16 at 04:12
  • You need to be careful when you say and cite "_The data is not very much_", remember that NSUserDefautls should be used only for a small pieces of data < 1MB aprox. In your case if you plan to save the complete object in some cases get/set the complete object in NSUserDefaults can be expensive. Anothe option can be write to file or use CoreData – Victor Sigler Jul 14 '16 at 04:14
  • Thanks guys, for the advice! Anyone know what the best solution would be to store something like this in file? NSkeyarchiver etc? – randomorb2110 Jul 14 '16 at 04:14
  • http://stackoverflow.com/questions/26469457/saving-custom-swift-class-with-nscoding-to-userdefaults – Mitul Marsoniya Jul 14 '16 at 04:15
  • use core data, easier to fetch and update data – xmhafiz Jul 14 '16 at 05:01

2 Answers2

1

Storing large amount of data in NSUserDefaults is not recommended. NSUserDefaults is meant to store small data like user preferences.

If you still want to proceed, You can use the below code compiled in Playground.


//: Playground - noun: a place where people can play

import UIKit

// Update your class to add encoder and decoder
class Place: NSObject, NSCoding {
    var name: String?
    var locationAddress: String?
    var locationPhoneNumber: String?

    init(name:String, locationAddress: String,locationPhoneNumber: String) {
        self.name = name
        self.locationAddress = locationAddress
        self.locationPhoneNumber = locationPhoneNumber
    }

    required convenience init(coder aDecoder: NSCoder) {

        let name = aDecoder.decodeObjectForKey("name") as! String
        let locationPhoneNumber = aDecoder.decodeObjectForKey("locationphonenumber") as! String
        let locationAddress = aDecoder.decodeObjectForKey("locationaddress") as! String
        self.init(name: name, locationAddress: locationAddress,  locationPhoneNumber: locationPhoneNumber)
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(locationAddress, forKey: "locationaddress")
        aCoder.encodeObject(locationPhoneNumber, forKey: "locationphonenumber")

    }
}


//Create your array of chosen place
let placesChosen = [Place(name: "India",locationAddress: "IndianAddress",locationPhoneNumber:"IndianPhoneNumber"), Place(name: "India",locationAddress: "IndianAddress",locationPhoneNumber:"IndianPhoneNumber")]


// Add your data to NSUser defaults
var userDefaults = NSUserDefaults.standardUserDefaults()
let encodedData = NSKeyedArchiver.archivedDataWithRootObject(placesChosen)
userDefaults.setObject(encodedData, forKey: "place")
userDefaults.synchronize()

// Retrieve your data from NSUserDefaults
if let decodedData = NSUserDefaults.standardUserDefaults().objectForKey("place") as? NSData {
    let decodedPlace = NSKeyedUnarchiver.unarchiveObjectWithData(decodedData) as! [Place]
    print(decodedPlace)

}

Adarsh V C
  • 2,314
  • 1
  • 20
  • 37
0

There are many solutions could be taken into consideration when it comes to storing data locally (in another word, might be data caching).

Firstly, you should consider life-cycle of your data. If the life-cycle is set alongside with application, you should simply use memory data storing as global variables.

If you want your data can be kept longer, you are able to use among possibilities including NSUserDefaults, CoreData and Save files to Disk.

NSUserdefaults is pretty easy and a fast way to use. I think it supposes to save lightweight data such as user's settings.

CoreData is a powerful tool but just in case of you want to store large, complex and relationship data. From your problem, I don't think it is a good deal.

Store in local disk as files either plist or any format is a quite good option for you. This is suitable for both small and huge amount of data.

To put it simply, I would suggest you to pass your objects as global variables if you don't want it to be saved persistently. Otherwise, please go with either NSUserdefaults or local disk. Please keep in mind that for custom objects, we need to implement NSCoding protocol for data serialization/deserialization and NSKeyedArchiver and NSKeyedUnarchiver for data encoding/decoding.

I hope this would be helpful.

HSG
  • 1,224
  • 11
  • 17