UserDefaults 保存字符串 -> 尝试将非 属性 列表对象(函数)设置为 NSUserDefaults/CFPreferences

UserDefaults save String -> Attempt to set a non-property-list object (Function) as an NSUserDefaults/CFPreferences

我在检索 UserDefaults 时收到上述错误消息。我将该值保存为字符串。 TimeInterval 转换为字符串。 问题出在哪里?

保存字符串的代码:

let timeResponse:TimeInterval = NSDate.timeIntervalSinceReferenceDate - start

let JSONTransferTime = TimeInterval.toReadableString(timeResponse) //converting to String

UserDefaults.standard.set(JSONTransferTime, forKey:"JSONTranferTime")

检索字符串的代码:

let JSONTransferTime: String = UserDefaults.standard.string(forKey: "JSONTranferTime")! as String

Utils.displayAlert(title: "JSON download time", message: JSONTransferTime)

确切的错误信息:

[User Defaults] Attempt to set a non-property-list object (Function) as an NSUserDefaults/CFPreferences value for key JSONTranferTime

toReadableString 的代码:

extension TimeInterval {

func toReadableString() -> String {

    // Nanoseconds
    let ns = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000000) % 1000
    // Microseconds
    let us = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000) % 1000
    // Milliseconds
    let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
    // Seconds
    let s = Int(self) % 60
    // Minutes
    let mn = (Int(self) / 60) % 60
    // Hours
    let hr = (Int(self) / 3600)

    var readableStr = ""
    if hr != 0 {
        readableStr += String(format: "%0.2dhr ", hr)
    }
    if mn != 0 {
        readableStr += String(format: "%0.2dmn ", mn)
    }
    if s != 0 {
        readableStr += String(format: "%0.2ds ", s)
    }
    if ms != 0 {
        readableStr += String(format: "%0.3dms ", ms)
    }
    if us != 0 {
        readableStr += String(format: "%0.3dus ", us)
    }
    if ns != 0 {
        readableStr += String(format: "%0.3dns", ns)
    }

    return readableStr
}

}

JSONTransferTime 变量已填充:

toReadableString() 是一个 instance 方法,你必须在 timeResponse 而不是 returns 函数的类型上调用它编译器顺便抱怨一下。

let jsonTransferTime = timeResponse.toReadableString()

请遵守变量名以小写字母开头的命名约定,不要注释编译器可以推断的类型。