简体   繁体   中英

Storing Data with NSUserDefaults Swift

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.

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)

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM