转换为Swift 3打破了自定义类编码/解码

时间:2016-09-15 11:30:11

标签: ios nsuserdefaults swift3 nscoding

所以我刚刚将一个小应用程序从Swift 2.2转换为Swift 3.我已经摆脱了自动转换器后所需的通常错误和拖把,但我有一个运行时问题,我可以没事。

我有一个自定义类,我使用NSCoding协议保存到NSUserDefaults。当我尝试从NSUserDefaults解码编码对象时,它在guard let duration = decoder.decodeObject(forKey: "duration") as? Int行上失败,因为持续时间打印为nil。解码标题字符串工作正常,但至少编码函数的这一行正常工作。

这在2.2中工作正常,我找不到任何迹象表明Swift 3对NSCoding进行了更改。任何帮助将不胜感激。

class TimerModel: NSObject, NSCoding, AVAudioPlayerDelegate {

    var name: String
    var active: Bool
    var paused: Bool
    var duration: Int
    var remainingWhenPaused: Int?
    var timerEndTime: Date?
    var timerStartTime: Date?
    var audioAlert: AlertNoise
    var UUID: String
    var colorScheme: BaseColor
    var alarmRepetitions: Int
    var timerRepetitions: Int
    var currentTimerRepetition: Int
    var audioPlaying: Bool
    var player: AVAudioPlayer = AVAudioPlayer()
    var countDownTimer: Timer = Timer()
    var delegate: timerProtocol? = nil

    init(withName name: String, duration: Int, UUID: String, color: BaseColor, alertNoise: AlertNoise, timerRepetitions: Int, alarmRepetitions: Int) {
        self.name = name
        self.active = false
        self.paused = false
        self.duration = duration
        self.UUID = UUID
        self.audioAlert = alertNoise
        self.colorScheme = color
        self.alarmRepetitions = alarmRepetitions
        self.audioPlaying = false
        self.timerRepetitions = timerRepetitions
        self.currentTimerRepetition = 0

        super.init()
    }

    convenience override init() {
        self.init(withName: "Tap Timer 1", duration: 10, UUID: Foundation.UUID().uuidString, color: .Red, alertNoise: .ChurchBell, timerRepetitions: 1, alarmRepetitions: 0)
    }

    // MARK: NSCoding

    required convenience init? (coder decoder: NSCoder) {
        print("in init coder:")
        print("Name: \(decoder.decodeObject(forKey: "name"))")
        print("Duration: \(decoder.decodeObject(forKey: "duration"))")
        guard let name = decoder.decodeObject(forKey: "name") as? String
        else {
            print("init coder name guard failed")
            return nil
        }
        guard let duration = decoder.decodeObject(forKey: "duration") as? Int
        else {
            print("init coder duration guard failed")
            print("duration: \(decoder.decodeObject(forKey: "duration"))")
            return nil
        }
        guard let audioAlertRawValue = decoder.decodeObject(forKey: "audioAlert") as? String
        else {
            print("init coder audioAlert guard failed")
            return nil
        }
        guard let UUID = decoder.decodeObject(forKey: "UUID") as? String
        else {
            print("init coder UUID guard failed")
            return nil
        }
        guard let colorSchemeRawValue = decoder.decodeObject(forKey: "colorScheme") as? String
        else {
            print("init coder colorScheme guard failed")
            return nil
        }
        guard let alarmRepetitions = decoder.decodeObject(forKey: "alarmRepetitions") as? Int
        else {
            print("init coder alarmRepetitions guard failed")
            return nil
        }
        guard let timerRepetitions = decoder.decodeObject(forKey: "timerRepetitions") as? Int
        else {
            print("init coder timerRepetitions guard failed")
            return nil
        }

        guard let audioAlert = AlertNoise(rawValue: audioAlertRawValue)
            else{
                print("No AlertNoise rawValue case found")
                return nil
        }
        guard let colorScheme = BaseColor(rawValue: colorSchemeRawValue)
            else{
                print("No BaseColor rawValue case found")
                return nil
        }

        print("initCoder guards passed, initing timer")
        print("\(name), \(duration), \(UUID), \(colorScheme), \(audioAlert), \(timerRepetitions), \(alarmRepetitions)")

        self.init(withName: name, duration: duration, UUID: UUID, color: colorScheme, alertNoise: audioAlert, timerRepetitions: timerRepetitions, alarmRepetitions: alarmRepetitions)
    }

    func encode(with aCoder: NSCoder) {

        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.duration, forKey: "duration")
        aCoder.encode(self.audioAlert.rawValue, forKey: "audioAlert")
        aCoder.encode(self.UUID, forKey: "UUID")
        aCoder.encode(self.colorScheme.rawValue, forKey: "colorScheme")
        aCoder.encode(self.alarmRepetitions, forKey: "alarmRepetitions")
        aCoder.encode(self.timerRepetitions, forKey: "timerRepetitions")
    }

2 个答案:

答案 0 :(得分:6)

所以看起来解决方案很简单,如果有点不直观。

所以我使用通用方法encode(self.ivar, forKey: "keyName")对类ivars进行编码,但是如果该ivar是一个int,则需要使用decodeInteger(forKey: "keyName")进行解码 - 这需要删除guard语句,因为这个方法返回非可选。如果使用通才方法解码,则看起来很奇怪必须用整数特定方法解码 - 这不是Swift 2.2中的情况。

答案 1 :(得分:1)

SimonBarker的优秀答案,它解决了我遇到的同样问题。我最终将他的解决方案应用于我自己的代码并对其进行了修改,以便使用通用方法完成编码。您可以使用以下方法使用通用方法“强制”编码:

func encode(_ objv: Any?, forKey key: String)

因此,在您的代码中,您可以使用:

aCoder.encode(self.name as Any?, forKey: "name")

这样self.name被编码为一个对象并且不会破坏你现有的代码,即:decoder.decodeObject(forKey:“name”)为?串

这可能不是最优雅的解决方案,但至少它对我有用而无需更改在Swift 2.3中运行良好的代码,但在Swift 3中被破坏了......