当前位置:网站首页>Swift saves an array of class objects with userdefaults and nssecurecoding

Swift saves an array of class objects with userdefaults and nssecurecoding

2022-07-05 10:09:00 cppphp

swift An array of class objects should be saved in the project , Selected after comprehensive consideration  UserDefaults And NSSecureCoding Save an array of class objects . First define the class :

class TimeData:NSObject, NSSecureCoding {
    static var supportsSecureCoding: Bool { return true } //  You need to add this static attribute 
    
    var time: Date
    var milliSecond: Int
    var appIndex: Int
    var state: Bool
    
    //  If you define an instance  TimeData, The print result will be the description string defined here 
    var descirption: String {
        return "\(self.time) \(self.milliSecond) \(appIndex) \(state)"
    }
    
    // TimeData  Construction method of class 
    required init(time:Date=Date(), milliSecond:Int=0, appIndex:Int = -1,state:Bool=true) {
        self.time = time
        self.milliSecond = milliSecond
        self.appIndex = appIndex
        self.state = state
    }

    //  Realization  NSCoding  In the agreement  init  and  encode  Method 
    //  from  object  Decode back 
    required init(coder decoder: NSCoder) {
        //  Notice what's coming back here  NSDate  type 
        self.time = decoder.decodeObject(of: NSDate.self, forKey: "time")! as Date
        
        //  about  Int  type ,  Use  decodeInteger  decode 
        self.milliSecond = decoder.decodeInteger(forKey: "milliSecond")
        self.appIndex = decoder.decodeInteger(forKey: "appIndex")
        
        //  about  Bool  type ,  Use  decodeBool  decode 
        self.state = decoder.decodeBool( forKey: "state")
    }

    //  Encoded as  object
    func encode(with coder: NSCoder) {
        coder.encode(time, forKey:"time")
        coder.encode(milliSecond, forKey:"milliSecond")
        coder.encode(appIndex, forKey: "appIndex")
        coder.encode(state, forKey: "state")
    }
}

And then in viewController Write in code :

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var times: Array<TimeData> = []
    
    override func viewDidLoad() {
        super.viewDidLoad()        

       // Monitoring into the background 
        NotificationCenter.default.addObserver(self, selector: #selector(didenterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        // The monitoring program is activated 
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    @objc func didenterBackground(){
        UserDefaults.standard.removeObject(forKey: "fireTime")
        if times.count > 0 {
            // The instance object is converted to Data
            let dataArray: NSMutableArray = []
            for time in times {
                do {
                    let data = try NSKeyedArchiver.archivedData(withRootObject: time, requiringSecureCoding: true)
                    dataArray.add(data)
                } catch {
                    fatalError("Failed to save \(time)...")
                }
            }
            let array: NSArray = NSArray(object: dataArray)
            UserDefaults.standard.set(array, forKey: "fireTime")
        }
    }
    
    @objc func didBecomeActive(){
        let array = UserDefaults.standard.object(forKey: "fireTime")
        if array != nil{
            times = []
            for arr in (array as! NSArray) {
                for data in arr as! NSArray {
                    do {
                        let time = try NSKeyedUnarchiver.unarchivedObject(ofClass: TimeData.self, from: data as! Data)
                        times.append( time!)
                    } catch {
                        fatalError("Failed to save \(String(describing: time))...")
                    }
                }
            }
            // vwTable.reloadData()
        }
    }
}

Through the above methods, the class object array is successfully saved .

Related blogs

《swift use UserDefaults And Codable  Save an array of class objects or structure instances 》

原网站

版权声明
本文为[cppphp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140534598073.html