当前位置:网站首页>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 》
边栏推荐
- 如何正确的评测视频画质
- ArcGIS Pro creating features
- TDengine 连接器上线 Google Data Studio 应用商店
- Tdengine connector goes online Google Data Studio app store
- 观测云与 TDengine 达成深度合作,优化企业上云体验
- From "chemist" to developer, from Oracle to tdengine, two important choices in my life
- 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
- 让AI替企业做复杂决策真的靠谱吗?参与直播,斯坦福博士来分享他的选择|量子位·视点...
- 小程序启动性能优化实践
- 搞数据库是不是越老越吃香?
猜你喜欢
把欧拉的创新带向世界 SUSE 要做那个引路人
Those who are good at using soldiers, hide in the invisible, and explain the best promotional value works in depth in 90 minutes
The popularity of B2B2C continues to rise. What are the benefits of enterprises doing multi-user mall system?
What should we pay attention to when entering the community e-commerce business?
Kotlin Compose 多个条目滚动
Understand the window query function of tdengine in one article
Getting started with Apache dolphin scheduler (one article is enough)
ArcGIS Pro creating features
苹果 5G 芯片研发失败?想要摆脱高通为时过早
Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 -下
随机推荐
百度智能小程序巡检调度方案演进之路
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
TDengine ×英特尔边缘洞见软件包 加速传统行业的数字化转型
Idea debugs com intellij. rt.debugger. agent. Captureagent, which makes debugging impossible
How Windows bat script automatically executes sqlcipher command
QT event filter simple case
Cent7 Oracle database installation error
Common fault analysis and Countermeasures of using MySQL in go language
苹果 5G 芯片研发失败?想要摆脱高通为时过早
How to use sqlcipher tool to decrypt encrypted database under Windows system
Theme. AppCompat. Light. Darkactionbar not found
Cerebral Cortex:有向脑连接识别帕金森病中广泛存在的功能网络异常
Kotlin Compose 与原生 嵌套使用
写入速度提升数十倍,TDengine 在拓斯达智能工厂解决方案上的应用
90%的人都不懂的泛型,泛型的缺陷和应用场景
卷起来,突破35岁焦虑,动画演示CPU记录函数调用过程
Develop and implement movie recommendation applet based on wechat cloud
Hard core, have you ever seen robots play "escape from the secret room"? (code attached)
Openes version query
B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条...