首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NSKeyedUnarchiver不会返回数据

NSKeyedUnarchiver不会返回数据
EN

Stack Overflow用户
提问于 2016-06-09 22:41:41
回答 1查看 801关注 0票数 0

我正在制作一个跟踪用户锻炼的应用程序。我有两个自定义类,第一个是ExerciseModel,,它保存锻炼期间执行的每个练习的数据,包括名称、集合、代表等等。下面是我的数据模型:

代码语言:javascript
运行
复制
import UIKit

class ExerciseModel: NSObject, NSCoding
{
// MARK: Properties
var name: String
var sets: Int
var reps: Int
var heartrate: Int?
var type: String?

//MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("exercises")


// MARK: Initialization
init?(name: String, sets: Int, reps: Int, heartrate: Int?, type: String)
{

// MARK: Initlaize stored properties
self.name = name
self.sets = sets
self.reps = reps
self.heartrate = heartrate
self.type = type

super.init()


// Initialization should fail if there is no name or sets is negative
if name.isEmpty || sets < 0
    {
        return nil
    }

}

struct PropertyKey
{
    static let nameKey = "name"
    static let setKey = "sets"
    static let repKey = "reps"
    static let heartrateKey = "heartrate"
    static let typekey = "type"
}


// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder)
{
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
    aCoder.encodeInteger(sets, forKey: PropertyKey.setKey)
    aCoder.encodeInteger(reps, forKey: PropertyKey.repKey)
    aCoder.encodeObject(type, forKey: PropertyKey.typekey)
}

required convenience init?(coder aDecoder: NSCoder)
{
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
    let sets = aDecoder.decodeIntegerForKey(PropertyKey.setKey)
    let reps = aDecoder.decodeIntegerForKey(PropertyKey.repKey)
    let heartrate = aDecoder.decodeIntegerForKey(PropertyKey.heartrateKey)
    let type = aDecoder.decodeObjectForKey(PropertyKey.typekey) as? String

    // Must call designated initializer
    self.init(name: name, sets: sets, reps: reps, heartrate: heartrate, type: type!)
}

init?(name: String, sets: Int, reps: Int, heartrate: Int, type: String)
{
    // Initialize stored properties.
    self.name = name
    self.sets = sets
    self.reps = reps
    self.heartrate = heartrate
    self.type = type

}


}

我的第二个自定义类名为WorkoutStorage,,这意味着允许用户保存整个训练并在以后检索它们。习题属性是上面描述的ExerciseModel对象的数组。以下是我的WorkoutStorage数据模型:

代码语言:javascript
运行
复制
//

import UIKit

@objc(WorkoutStorage)
class WorkoutStorage: NSObject, NSCoding
{
// MARK: Properties
var name: String
var date: NSDate
var exercises: [ExerciseModel]
var maxHR: Int
var avgHR: Int

// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("storedWorkouts")

// MARK: Initialization
init?(name: String, date: NSDate, exercises: [ExerciseModel], maxHR: Int, avgHR: Int)
{
    //MARK: Initialize Stored Properties
    self.name = name
    self.date = date
    self.exercises = exercises
    self.maxHR = maxHR
    self.avgHR = avgHR

    super.init()

}

struct PropertyKey
{
    static let nameKey = "name"
    static let dateKey = "date"
    static let exercisesKey = "exercises"
    static let maxHRKey = "maxHR"
    static let avgHRKey = "avgHR"
}

// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder)
{
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
    aCoder.encodeObject(date, forKey: PropertyKey.dateKey)
    aCoder.encodeObject(exercises, forKey: PropertyKey.exercisesKey)
    aCoder.encodeInteger(maxHR, forKey: PropertyKey.maxHRKey)
    aCoder.encodeInteger(avgHR, forKey: PropertyKey.avgHRKey)
}

required convenience init?(coder aDecoder: NSCoder)
{
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
    let date = aDecoder.decodeObjectForKey(PropertyKey.dateKey) as! NSDate
    let exercises = aDecoder.decodeObjectForKey(PropertyKey.exercisesKey) as! [ExerciseModel]
    let maxHR = aDecoder.decodeIntegerForKey(PropertyKey.maxHRKey)
    let avgHR = aDecoder.decodeIntegerForKey(PropertyKey.avgHRKey)

    // Must call designated initializer
    self.init(name: name, date: date, exercises: exercises, maxHR: maxHR, avgHR: avgHR)
}
}

我学习了Apple教程中的持久化数据来设置NSKeyedArchiver和NSKeyedUnarchiver,但是我仍然很难检索到数据。当我尝试加载训练时,我调用以下函数:

代码语言:javascript
运行
复制
func loadStoredWorkouts() -> WorkoutStorage
{
    NSKeyedUnarchiver.setClass(WorkoutStorage.self, forClassName: "WorkoutStorage")
    NSKeyedArchiver.setClassName("WorkoutStorage", forClass: WorkoutStorage.self)

    print("\(WorkoutStorage.ArchiveURL.path!)")

    return NSKeyedUnarchiver.unarchiveObjectWithFile(WorkoutStorage.ArchiveURL.path!) as! WorkoutStorage
}

目前我只能返回一个WorkoutStorage对象,但是当我试图检索一个包含所有存储的WorkoutStorage对象的数组时,我会收到一个错误消息:不能将'Workout_Tracker.WorkoutStorage‘(0x1000fcc80)类型的值转换为'NSArray’(0x19f6b2418)。我阅读了很多文档,试图找出为什么这只会返回一个对象,以及检查出类似问题的问题,但都没有用。最初,我按照教程设置了我的应用程序来存储和加载我的ExerciseModel对象,这似乎是完美无缺的。我以同样的方式设置了WorkoutStorage类,但这里似乎存在一个问题。

任何帮助都将不胜感激!!

**Edit*下面是我用来归档WorkoutStorage对象的代码:

代码语言:javascript
运行
复制
func saveWorkoutStorageObject(currentWorkout: WorkoutStorage)
    {
        NSKeyedUnarchiver.setClass(WorkoutStorage.self, forClassName: "WorkoutStorage")
        NSKeyedArchiver.setClassName("WorkoutStorage", forClass: WorkoutStorage.self)

    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(currentWorkout, toFile: WorkoutStorage.ArchiveURL.path!)
    if !isSuccessfulSave
    {
        print("Failed to save exercises")
    }
    if isSuccessfulSave
    {
        print("Successful save of current workout: \(currentWorkout)")
    }
}

用户每次只创建一个锻炼,所以每次完成时,我都会将对象传递给上面的函数来存档。

为了对所有对象进行解压缩,我试图按以下方式进行如下操作:

代码语言:javascript
运行
复制
var workouts = [WorkoutStorage]()

override func viewDidLoad()
{
    super.viewDidLoad()

    workouts = loadStoredWorkouts()
}

其中loadStoredWorkouts()函数为:

代码语言:javascript
运行
复制
 func loadStoredWorkouts() -> [WorkoutStorage]
    {
        NSKeyedUnarchiver.setClass(WorkoutStorage.self, forClassName: "WorkoutStorage")
        NSKeyedArchiver.setClassName("WorkoutStorage", forClass: WorkoutStorage.self)

    print("\(WorkoutStorage.ArchiveURL.path!)")

    return NSKeyedUnarchiver.unarchiveObjectWithFile(WorkoutStorage.ArchiveURL.path!) as! [WorkoutStorage]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-09 23:31:50

你的saveWorkoutStorageObject只记录了一次锻炼。它不对数组进行存档,因此当然不能将数组解压缩。

如果希望能够解压缩数组,则需要对workouts数组进行归档。

每次将某些文件存档到文件中时,都会替换该文件的内容。它没有附加到结尾。

由于NSKeyedArchiver.archiveRootObject自动归档子对象,所以您所需要做的就是归档数组,并且WorkoutStorage对象将自动归档。

代码语言:javascript
运行
复制
func saveWorkouts(workouts:[WorkoutStorage])
{
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(workouts, toFile: WorkoutStorage.ArchiveURL.path!)
    if isSuccessfulSave
    {
        print("Successful save of workouts: \(workouts)")
    } else {
        print("Failed to save exercises")
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37737351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档