ios - 在 Swift 3.1 中将自己的对象数组添加到 UserDefaults 时出错

标签 ios swift nscoding

不幸的是,我无法将我自己的类对象列表添加到 UserDefaults。生成以下错误:

NSForwarding: warning: object 0x6080002502c0 of class 'ClrLearn.highscoreStructure' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector -[ClrLearn.highscoreStructure >replacementObjectForKeyedArchiver:]

该类如下所示(已根据堆栈上的各种主题进行了修改,例如那个 - how can store custom objects in NSUserDefaults ):

class highscoreStructure {
    var name : String = ""
    var score : Int = 0

    init(name: String, score: Int) {
        self.name = name
        self.score = score
    }

    required init(coder decoder: NSCoder) {
        self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
        self.score = decoder.decodeInteger(forKey: "score")
    }

    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(score, forKey: "score")
    }
}

好吧,感觉我在 Stack 规则上做错了,所以对不起 rmaddy - 这是第一次也是最后一次,我保证。 :)

但回到问题上来,第一部分由 vadian 解决了 - 非常感谢!但是我的应用程序的那部分仍然不起作用: 我已经将 rootObject (NSKeyedArchiver.archivedData(withRootObject: highscoreStructObjects)) 设置为我的对象数组(如此愚蠢的错误!)但仍然有这样的错误:

[ClrLearn.HighscoreStructure encodeWithCoder:]: unrecognized selector sent >to instance 0x6080002586c0

Terminating app due to uncaught exception 'NSInvalidArgumentException', >reason: '-[ClrLearn.HighscoreStructure >encodeWithCoder:]: unrecognized >selector sent to instance >0x6080002586c0' –

附言。我不确定这是我应该出错的地方 - 调试日志对我来说仍然不清楚,至少不像 Visual Studio 中的那样干净。 :) 也许我应该粘贴其他内容?

Pps。这行代码看起来像:

let encodedData = NSKeyedArchiver.archivedData(withRootObject:     highscoreStructObjects)
UserDefaults.standard.set(encodedData, forKey: "highscores")

最佳答案

为了能够实现NSCoding,类必须继承自NSObject

class HighscoreStructure : NSObject { ...

顺便说一句,类名应该以大写字母开头。

而且 decodeObject(forKey: "name") 永远不会是 nil 你可以安全地写

self.name = decoder.decodeObject(forKey: "name") as! String

关于ios - 在 Swift 3.1 中将自己的对象数组添加到 UserDefaults 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066630/

相关文章:

ios - 检测 RACSignal 的最佳实践

ios - Apple 更改了 Metal 中允许的矢量格式

iphone - 存储多个关联在一起的数组的最佳方式 - Objective C

ios - 如何在 UITableViewCell 中添加注释文本?

iphone - 无法弄清楚为什么我的应用程序在使用 NSKeyedArchivers/NSKeyedUnarchivers 时崩溃

ios - 使用在 NSObject 类上创建的 ASIHTTPRequest 添加下载进度条

ios - 在 swift 2.0 iOS 中使用 peek 和 pop 时如何更改模糊 View 的背景颜色

swift - 删除或编辑用户位置蓝色脉冲圆圈

swift - 添加 NSCoding 作为扩展

arrays - 检索数组功能不起作用