Как сохранить весь объект в NSUserDefaults

Я использую 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 и получить его позже?


person Byte    schedule 26.09.2016    source источник
comment
stackoverflow.com/questions/2315948 / Взгляните на это   -  person Shayan Jalil    schedule 26.09.2016
comment
Я видел эти ответы, но они не кажутся мне оптимизированным подходом, потому что мне нужно сохранять все с помощью отдельного ключа. Я хочу сохранить весь объект по ключу и просто вернуть его.   -  person Byte    schedule 26.09.2016
comment
NSUserDefaults может хранить только – NSArray – NSData – NSDictionary – NSNumber – NSString Кроме того, NSArray или NSDictionary должны содержать только типы, перечисленные выше. Поэтому вам нужно преобразовать свою структуру в NSDictionary или вместо этого сохранить ответ JSON.   -  person Roman    schedule 26.09.2016


Ответы (1)


Если вы хотите сохранить свой объект как отдельный объект, ваш способ должен соответствовать 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
}
person RyuX51    schedule 26.09.2016