gpt4 book ai didi

swift - NSCoder 无法解码 Float

转载 作者:行者123 更新时间:2023-11-30 12:48:02 28 4
gpt4 key购买 nike

我定义了一个具有 [String] 和 Float 属性的类,它在 NSCoder 的编码过程中工作正常,但在解码时总是失败。我在代码中添加了guard let,发现是Float $的问题。

我不知道Float出了什么问题,我确实看到了一些问题Fail to decode Int with NSCoder in Swift网上说它与可选属性有关,但在我的情况下它不是可选变量。

如有任何建议,我们将不胜感激。

import UIKit
class aBill : NSObject, NSCoding {
//MARK: - Properties
var payer: [String]
var getter: [String]
var $: Float

struct PropertyKey {
static let payer = "payer"
static let getter = "getter"
static let money = "$"
}

// MARK: - Initialization
init?(payer: [String], getter: [String], $: Float) {
// Initialize stored properties.
self.payer = payer
self.getter = getter
self.$ = $
self.currency = currency
self.remark = itemName

super.init()

}

//MARK: - NSCoding properties
func encode(with aCoder: NSCoder) {
aCoder.encode(payer, forKey: PropertyKey.payer)
aCoder.encode(getter, forKey: PropertyKey.getter)
aCoder.encode($, forKey: PropertyKey.money)
}

required convenience init?(coder aDecoder: NSCoder) {

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let payer = aDecoder.decodeObject(forKey: PropertyKey.payer) as? [String]
else {
print("Unable to decode the payer name for a aBill object.")
return nil
}

guard let getter = aDecoder.decodeObject(forKey: PropertyKey.getter) as? [String]
else {
print("Unable to decode the getter name for a aBill object.")
return nil
}
guard let money = aDecoder.decodeObject(forKey: PropertyKey.money) as? Float
else {
print("Unable to decode the $ for a aBill object. ")
return nil
}

print("Start convenience init")
self.init(payer: payer, getter: getter, $: money)
print("Sucess convenience init")
}

//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("aBill")}

}

最佳答案

你可以尝试一下aCoder.encode(<#T##realv: Float##Float#>, forKey: <#T##String#>)和aDecoder.decodeFloat(forKey: <#T##String#>)因为ecodeforkey是针对对象的。

关于swift - NSCoder 无法解码 Float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41372834/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com