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

时间:2019-03-01 10:07:03

标签: swift nsuserdefaults nstimeinterval

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

保存字符串的代码:

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变量已填充:

Alert to show downloadtime

1 个答案:

答案 0 :(得分:1)

toReadableString()是一个实例方法,您必须在timeResponse上调用它,而不是在返回编译器抱怨的函数的类型上调用它。 / p>

let jsonTransferTime = timeResponse.toReadableString()

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