IOS:从userDefaults和NSCoding中检索自定义对象会给出不同的值

时间:2017-04-24 07:35:15

标签: ios swift3 nsuserdefaults nscoding

我正在尝试在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")

    }

 ....
}

0 个答案:

没有答案