如何在NSUserDefaults中保存整个对象

时间:2016-09-26 07:21:33

标签: ios swift nsuserdefaults nscoding objectmapper

我正在使用ObjectMapper从我的服务器映射JSON响应。这是我的数据模型。

class HomeStats: Mappable {

// MARK: - Constants & Variables

var todayText: String
var pointsText: String
var todayActivitiesText: String
var totalPointsText: String
var rewardsText: String
var myStatsText: String
var motivationalMessage: String

var todaySteps: String
var todayStepPoints: String
var stepsText : String
var todayTotalPoints: Double
var allPoints: String

var userRegistrationDate: String
var firstTrackerConnectionDate: String

var userID:Int
.
.
.

等等。我在班上用这个

// init
let allStats = Mapper<HomeStats>().map([:])!

// usage
if let data = Mapper<HomeStats>().map(result){ // result is my JSON responce
      self.allStats = data;
}

现在我如何将我的整个对象allStats存储到NSUserDefaults并稍后检索?

1 个答案:

答案 0 :(得分:0)

如果您想将对象保存为单个对象,则应遵循NSCoding

class HomeStats: NSObject, Mappable, NSCoding {

    // add to your class HomeStats

    required init?(coder aDecoder: NSCoder) {
        todayText = aDecoder.decodeObjectForKey(todayText) as! String
        pointsText = aDecoder.decodeObjectForKey(pointsText) as! String
        todayActivitiesText = aDecoder.decodeObjectForKey(todayActivitiesText) as! String
        totalPointsText = aDecoder.decodeObjectForKey(totalPointsText) as! String
        rewardsText = aDecoder.decodeObjectForKey(rewardsText) as! String
        myStatsText = aDecoder.decodeObjectForKey(myStatsText) as! String
        motivationalMessage = aDecoder.decodeObjectForKey(motivationalMessage) as! String

        todaySteps = aDecoder.decodeObjectForKey(todaySteps) as! String
        todayStepPoints = aDecoder.decodeObjectForKey(todayStepPoints) as! String
        stepsText = aDecoder.decodeObjectForKey(stepsText) as! String
        todayTotalPoints = aDecoder.decodeDoubleForKey(todayTotalPoints) as! Double
        allPoints = aDecoder.decodeObjectForKey(allPoints) as! String

        userRegistrationDate = aDecoder.decodeObjectForKey(userRegistrationDate) as! String
        firstTrackerConnectionDate = aDecoder.decodeObjectForKey(firstTrackerConnectionDate) as! String

        userID = aDecoder.decodeIntForKey(userID, forKey: "userID") as! Int
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(todayText, forKey: "todayText")
        aCoder.encodeObject(pointsText, forKey: "pointsText")
        aCoder.encodeObject(todayActivitiesText, forKey: "todayActivitiesText")
        aCoder.encodeObject(totalPointsText, forKey: "totalPointsText")
        aCoder.encodeObject(rewardsText, forKey: "rewardsText")
        aCoder.encodeObject(myStatsText, forKey: "myStatsText")
        aCoder.encodeObject(motivationalMessage, forKey: "motivationalMessage")

        aCoder.encodeObject(todaySteps, forKey: "todaySteps")
        aCoder.encodeObject(todayStepPoints, forKey: "todayStepPoints")
        aCoder.encodeObject(stepsText, forKey: "stepsText")
        aCoder.encodeDouble(todayTotalPoints, forKey: "todayTotalPoints")
        aCoder.encodeObject(allPoints, forKey: "allPoints")

        aCoder.encodeObject(userRegistrationDate, forKey: "userRegistrationDate")
        aCoder.encodeObject(firstTrackerConnectionDate, forKey: "firstTrackerConnectionDate")

        aCoder.encodeInteger(userID, forKey: "userID")
    }
}

// save and load your serialised file wherever you wish with something like this:

let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
let filePath = documentsDirectory.appendingPathComponent("filename")

// serialise and save your instance
func storeHomeStats(homeStats: HomeStats) {
    let data = NSKeyedArchiver.archivedData(withRootObject: homeStats)

    do {
        try data.write(to: filePath)
    } catch let error as NSError {
        print("Couldn't write file: \(error)")
    }
}

// deserialise your instance
func loadHomeStats() -> HomeStats? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? HomeStats
}