无法将自定义类数组保存到UserDefaults

时间:2019-03-03 18:50:48

标签: ios swift xcode nsuserdefaults swift4.2

我正在尝试将自定义类数组保存到UserDefaults,但是它不起作用。我没有得到if let的奖励。我在网上到处看。我正在使用Swift 4.2

extension UserDefaults {
    func saveReciters(_ reciters: [Reciter]) {
        do {
            let encodedData = try NSKeyedArchiver.archivedData(withRootObject: reciters, requiringSecureCoding: false)
            self.set(encodedData, forKey: UD_RECITERS)
        } catch {
            debugPrint(error)
            return
        }
    }

    func getReciters() -> [Reciter] {
        if let reciters = self.object(forKey: UD_RECITERS) as? Data {
            return NSKeyedUnarchiver.unarchiveObject(with: reciters) as! [Reciter]
        } else {
            print("EMPTY RECITERS")
            return [Reciter]()
        }
    }
}
  
    

UserInfo = {NSDebugDescription =存档期间捕获到异常:-[_ SwiftValue encodeWithCoder:]:无法识别的选择器已发送到实例0x600001babcc0

  

那是我的课:

class Reciter: NSCoding {

private(set) public var name: String
private(set) public var image: UIImage?
private(set) public var surahs: [Surah]
private(set) public var documentID: String

private let quranData = QuranData()

init(name: String, image: UIImage?, surahCount: Int?, documentID: String) {
    self.name = name
    self.image = image
    self.documentID = documentID

    if let surahCount = surahCount {
        surahs = Array(quranData.getAllSurahs().prefix(surahCount))
    } else {
        surahs = quranData.getAllSurahs()
    }
}

func encode(with aCoder: NSCoder) {

}

required init?(coder aDecoder: NSCoder) {

}
}

在我的《古兰经》课上,我得零分。我成功获得所有其他财产 enter image description here

1 个答案:

答案 0 :(得分:0)

我经常看到开发人员使用codeable,这里我以用户为例:

YourDataModel.swift

struct User: Codable {
    var userId: String = ""
    var name: String = ""
    var profileImageData: Data? }

UserDefaults.swift

import Foundation

extension UserDefaults {

    /// The current user of the application, see `./Models/User.swift`
    var currentUser: User? {
        get {
            guard let userData = self.object(forKey: #function) as? Data else { return nil }
            return try? JSONDecoder().decode(User.self, from: userData)
        }

        set {
            guard let newuser = newValue else { return }
            if let userData = try? JSONEncoder().encode(newuser) {
                self.set(userData, forKey: #function)
            }
        }
    }

}

将数据转换为json数据... #function是函数或值名称,即

    // For the case the user doesn't yet exist.
    if ( UserDefaults.standard.currentUser == nil )  {
        // Create a new user
        user = User()
        // Generate an id for the user, using a uuid.
        user?.userId = UUID().uuidString
    } else {
        // otherwise, fetch the user from user defaults.
        user = UserDefaults.standard.currentUser
    }