我已经使用[String]和Float属性定义了一个类,它在NSCoder的编码过程中运行良好,但它总是因解码而失败。 我已经将守卫添加到代码中,并找到了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")}
}
答案 0 :(得分:0)
答案 1 :(得分:0)