当前位置:网站首页>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 》
边栏推荐
- Wechat applet - simple diet recommendation (4)
- 【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值
- Solve liquibase – waiting for changelog lock Cause database deadlock
- TDengine × Intel edge insight software package accelerates the digital transformation of traditional industries
- mysql80服务不启动
- cent7安装Oracle数据库报错
- From "chemist" to developer, from Oracle to tdengine, two important choices in my life
- MySQL character type learning notes
- How to correctly evaluate video image quality
- 为什么不建议你用 MongoDB 这类产品替代时序数据库?
猜你喜欢
Develop and implement movie recommendation applet based on wechat cloud
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
【技术直播】如何用 VSCode 从 0 到 1 改写 TDengine 代码
高级 OpenCV:BGR 像素强度图
【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
Node red series (29): use slider and chart nodes to realize double broken line time series diagram
Meitu lost 300 million yuan in currency speculation for half a year. Huawei was exposed to expand its enrollment in Russia. Alphago's peers have made another breakthrough in chess. Today, more big new
[tips] get the x-axis and y-axis values of cdfplot function in MATLAB
Online chain offline integrated chain store e-commerce solution
历史上的今天:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生...
随机推荐
Theme. AppCompat. Light. Darkactionbar not found
如何獲取GC(垃圾回收器)的STW(暫停)時間?
MySQL字符类型学习笔记
Tianlong Babu TLBB series - questions about skill cooling and the number of attack ranges
C#函数返回多个值方法
90%的人都不懂的泛型,泛型的缺陷和应用场景
Roll up, break 35 - year - old Anxiety, animation Demonstration CPU recording Function call Process
Apache dolphin scheduler system architecture design
QT realizes signal transmission and reception between two windows
【系统设计】指标监控和告警系统
Design and exploration of Baidu comment Center
解决idea调试过程中liquibase – Waiting for changelog lock….导致数据库死锁问题
Flutter development: a way to solve the problem of blank space on the top of listview
Charm of code language
自动化规范检查软件如何发展而来?
About getfragmentmanager () and getchildfragmentmanager ()
基于单片机步进电机控制器设计(正转反转指示灯挡位)
历史上的今天:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生...
Wechat applet - simple diet recommendation (2)
Solve the problem of no all pattern found during Navicat activation and registration