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

本文介绍了如何在 Swift 工程中使用 UserDefaults 结合 NSSecureCoding 来实现类对象数组的持久化存储。通过定义类并实现 NSSecureCoding 协议,然后在 ViewController 中进行编码和解码操作,成功保存和读取类对象数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<TimeData> = []
    
    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 用 UserDefaults 及 Codable 保存类对象或结构实例数组》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值