我正在尝试在UserDefaults中保存自定义对象,当我打印对象时,检索到的对象Id与保存对象不同。下面是代码。
保存
let customAlertView:CustomAlertView = CustomAlertView()
customAlertView.buyingRoleInnerStackView = contextInnerItem
customAlertView.buyingRoleInnerArrStackView = contextArrInnerItem
print("customAlertView :: \(customAlertView)")
// - > 打印customAlertView :: CustomAlertView: 0x1702bc9e0 >
let encodedData = NSKeyedArchiver.archivedData(withRootObject: customAlertView)
let defaults = UserDefaults.standard
defaults.set(encodedData, forKey: AppConstants().KEY_CUSTOM_ALERT_VIEW)
Retriving
let defaults = UserDefaults.standard
if let viewData = defaults.object(forKey: AppConstants().KEY_CUSTOM_ALERT_VIEW) as? Data {
let alertView = NSKeyedUnarchiver.unarchiveObject(with: viewData) as! CustomAlertView
print("alertView :: \(alertView)")
}
// - > 打印alertView :: CustomAlertView: 0x1702be120 > }
CustomAlertView类
class CustomAlertView :NSObject, NSCoding {
var buyingRoleInnerStackView:UIStackView!
var buyingRoleInnerArrStackView:UIStackView!
override init() {}
required init(coder aDecoder: NSCoder) {
self.buyingRoleInnerStackView = aDecoder.decodeObject(forKey: "buyingRoleInnerStackView") as! UIStackView
self.buyingRoleInnerArrStackView = aDecoder.decodeObject(forKey: "buyingRoleInnerArrStackView") as! UIStackView
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.buyingRoleInnerStackView, forKey: "buyingRoleInnerStackView")
aCoder.encode(self.buyingRoleInnerArrStackView, forKey: "buyingRoleInnerArrStackView")
}
....
}