本文介绍了在数组上使用 NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NSUserDefaults 将数组保存到我的应用程序的核心数据中.我认为使用 NSUserDefaults 会很好,但问题是,无论我将创建默认值的代码放在何处,都会引发 SIGABRT 错误.

I am trying to use NSUserDefaults to save an array in to my app's core data. I thought it would be good to use NSUserDefaults but the problem is that wherever I put the code that creates the default it throws up the SIGABRT error.

这是创建默认值的代码:

Here is the code that creates the default:

let levelArrayDefault = NSUserDefaults.standardUserDefaults()
    levelArrayDefault.setValue(levelsArray, forKey: "levelsArray")
    levelArrayDefault.synchronize()

levelsArray 是一个 List 对象数组:

levelsArray is an array of List objects:

    class List: NSObject, NSCoding {
    // MARK: Properties
    var name: String
    var AnswersArray = [Answer]()


    init?(name: String) {
        // Initialize stored properties.
        self.name = name

        if name.isEmpty {
            return nil
        }

    }

    required init(coder decoder: NSCoder){
        self.AnswersArray = (decoder.decodeObjectForKey("AA") as? [Answer])!
        self.name = (decoder.decodeObjectForKey("name") as? String)!
    }
    func encodeWithCoder(coder: NSCoder) {
        if let AnswersArray = AnswersArray { coder.encodeObject(AnswersArray, forKey: "AA") }
        if let name = name { coder.encodeObject(name, forKey: "name") }
    }


}
class Answer: NSObject, NSCoding {
    var EnglishAnswer: String = ""
    var ChineseAnswer: String = ""
    init(newEng: String, newChi: String){
        self.EnglishAnswer = newEng
        self.ChineseAnswer = newChi
    }
    required init(coder decoder: NSCoder){
        self.EnglishAnswer = (decoder.decodeObjectForKey("EnglishAnswer") as? String)!
        self.ChineseAnswer = (decoder.decodeObjectForKey("ChineseAnswer") as? String)!
    }
    func encodeWithCoder(coder: NSCoder) {
        if let EnglishAnswer = EnglishAnswer { coder.encodeObject(EnglishAnswer, forKey: "EnglishAnswer") }
        if let ChineseAnswer = ChineseAnswer { coder.encodeObject(ChineseAnswer, forKey: "ChineseAnswer") }
    }

}

如何阻止 SIGABRT 弹出并获取要存储的数组.非常感谢您的帮助.

How can I stop SIGABRT from popping up and get the array to be stored.Help would be much appreciated.

推荐答案

在存储到 NSUserDefaults 之前,您需要使用 NSKeyedArchiver 将其转换为 NSData,尝试如下:

You need to convert it to NSData using NSKeyedArchiver before storing it to NSUserDefaults, try like this:

更新:Xcode 11.4 • Swift 5.2 或更高版本

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let list = List(name: "Student")
        list.answers = [Answer(english: "english answer", chinese: "中文回答")]
        let data = (try? NSKeyedArchiver.archivedData(withRootObject: [list], requiringSecureCoding: false)) ?? Data()
        UserDefaults.standard.set(data, forKey: "listData")
        guard
            let loadedData = UserDefaults.standard.data(forKey: "listData"),
            let loadedArray = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(loadedData) as? [List]
            else { return }
        print(loadedData.count)
        print(loadedArray.first ?? "none")
        print(loadedArray.first?.name ?? "no name")
        print(loadedArray.first?.answers.first?.english ?? "no english")
        print(loadedArray.first?.answers.first?.chinese ?? "no chinese")
    }
}


class Answer: NSObject, NSCoding {
    let english: String
    let chinese: String
    init(english: String, chinese: String) {
        self.english = english
        self.chinese = chinese
    }
    required init(coder decoder: NSCoder) {
        self.english = decoder.decodeString(forKey: "english")
        self.chinese = decoder.decodeString(forKey: "chinese")
    }
    func encode(with coder: NSCoder) {
        coder.encode(english, forKey: "english")
        coder.encode(chinese, forKey: "chinese")
    }
}


class List: NSObject, NSCoding {
    let name: String
    fileprivate var data = Data()
    var answers: [Answer] {
        get {
            (try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)) as? [Answer] ?? []
        }
        set {
            data = (try? NSKeyedArchiver.archivedData(withRootObject: newValue, requiringSecureCoding: false)) ?? Data()
        }
    }
    init(name: String) {
        self.name = name
    }
    required init(coder decoder: NSCoder) {
        self.data = decoder.decodeData(forKey: "answersData")
        self.name = decoder.decodeString(forKey: "name")
    }
    func encode(with coder: NSCoder) {
        coder.encode(data, forKey: "answersData")
        coder.encode(name, forKey: "name")
    }
}


extension NSCoder {
    func decodeString(forKey key: String) -> String {
        return decodeObject(forKey: key) as? String ?? ""
    }
    func decodeData(forKey key: String) -> Data {
        return decodeObject(forKey: key) as? Data ?? Data()
    }
}

这篇关于在数组上使用 NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:20