swift 用 UserDefaults 及 NSSecureCoding 保存类对象数组

swift 工程中要保存类对象数组,经综合考虑选用 UserDefaults 及 NSSecureCoding 保存类对象数组。首先定义类:

class TimeData:NSObject, NSSecureCoding {
    static var supportsSecureCoding: Bool { return true } // 需要添加这个静态属性
    
    var time: Date
    var milliSecond: Int
    var appIndex: Int
    var state: Bool
    
    // 如果定义一个实例 TimeData,打印结果将是这里定义的描述字符串
    var descirption: String {
        return "\(self.time) \(self.milliSecond) \(appIndex) \(state)"
    }
    
    // TimeData 类的构造方法
    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
    }

    // 实现 NSCoding 协议中的 init 和 encode 方法
    // 由 object 解码回来
    required init(coder decoder: NSCoder) {
        // 注意这里返回的是 NSDate 类型
        self.time = decoder.decodeObject(of: NSDate.self, forKey: "time")! as Date
        
        // 对于 Int 类型, 要用 decodeInteger 解码
        self.milliSecond = decoder.decodeInteger(forKey: "milliSecond")
        self.appIndex = decoder.decodeInteger(forKey: "appIndex")
        
        // 对于 Bool 类型, 要用 decodeBool 解码
        self.state = decoder.decodeBool( forKey: "state")
    }

    // 编码为 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")
    }
}

然后在 viewController 中写代码:

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

       //监测进入后台
        NotificationCenter.default.addObserver(self, selector: #selector(didenterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        //监测程序被激活
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    @objc func didenterBackground(){
        UserDefaults.standard.removeObject(forKey: "fireTime")
        if times.count > 0 {
            //实例对象转换成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()
        }
    }
}

通过以上方法成功的保存了类对象数组。

你可能感兴趣的:(Swift)