当前位置:网站首页>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 》
边栏推荐
- How to get the STW (pause) time of GC (garbage collector)?
- The popularity of B2B2C continues to rise. What are the benefits of enterprises doing multi-user mall system?
- 卷起来,突破35岁焦虑,动画演示CPU记录函数调用过程
- What should we pay attention to when entering the community e-commerce business?
- 如何獲取GC(垃圾回收器)的STW(暫停)時間?
- Tdengine offline upgrade process
- 程序员搞开源,读什么书最合适?
- Evolution of Baidu intelligent applet patrol scheduling scheme
- Wechat applet - simple diet recommendation (4)
- [technical live broadcast] how to rewrite tdengine code from 0 to 1 with vscode
猜你喜欢
如何获取GC(垃圾回收器)的STW(暂停)时间?
Application of data modeling based on wide table
历史上的今天:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生...
Officially launched! Tdengine plug-in enters the official website of grafana
一文读懂TDengine的窗口查询功能
RMS TO EAP通过MQTT简单实现
RMS to EAP is simply implemented through mqtt
Analysis on the wallet system architecture of Baidu trading platform
View Slide
Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常
随机推荐
. Net delay queue
Design and exploration of Baidu comment Center
QT event filter simple case
Mysql80 service does not start
【C语言】动态内存开辟的使用『malloc』
How do enterprises choose the appropriate three-level distribution system?
Tdengine already supports the industrial Intel edge insight package
TDengine 连接器上线 Google Data Studio 应用商店
Coffeescript Chinese character to pinyin code
ThreadLocal source code learning
Small program startup performance optimization practice
从“化学家”到开发者,从甲骨文到 TDengine,我人生的两次重要抉择
Online chain offline integrated chain store e-commerce solution
Those who are good at using soldiers, hide in the invisible, and explain the best promotional value works in depth in 90 minutes
如何獲取GC(垃圾回收器)的STW(暫停)時間?
Oracle combines multiple rows of data into one row of data
TDengine可通过数据同步工具 DataX读写
Pagoda panel MySQL cannot be started
Why don't you recommend using products like mongodb to replace time series databases?
Comparison of batch merge between Oracle and MySQL