Save struct in class to NSUserDefaults using Swift(使用 Swift 将类中的结构保存到 NSUserDefaults)
问题描述
我有一个类,类里面是一个(swift)数组,基于一个全局结构.我想将这个类的数组保存到 NSUserDefaults.这是我的代码:
I have a class and inside the class is a (swift) array, based on a global struct. I want to save an array with this class to NSUserDefaults. This is my code:
struct mystruct {
var start : NSDate = NSDate()
var stop : NSDate = NSDate()
}
class MyClass : NSObject {
var mystructs : [mystruct]
init(mystructs : [mystruct]) {
self.mystructs = mystructs
super.init()
}
func encodeWithCoder(encoder: NSCoder) {
//let val = mystructs.map { $0 as NSObject } //this also doesn't work
let objctvtmrec = NSMutableArray(mystructs) //gives error
encoder.encodeObject(objctvtmrec)
//first approach:
encoder.encodeObject(mystructs) //error: [mystructs] doesn't conform to protocol 'anyobject'
}
}
var records : [MyClass] {
get {
var returnValue : [MyClass]? = NSUserDefaults.standardUserDefaults().objectForKey("records") as? [MyClass]
if returnValue == nil
{
returnValue = []
}
return returnValue!
}
set (newValue) {
let val = newValue.map { $0 as AnyObject }
NSUserDefaults.standardUserDefaults().setObject(val, forKey: "records")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
我已经继承了 NSObject,并且我知道我需要 NSCoding.但我没有找到任何方法将结构数组转换为 NSMuteableArray 或我可以存储的类似内容.到目前为止,唯一的想法是遍历每个条目并将其直接复制到一个新数组中,或者在整个项目中使用大量或 Objective-c 代码,因此我不需要从 swift 数组转换为 Objective-c 数组.两者都是我不想做的事情.
I already subclassed to NSObject, and I know I need NSCoding. But I don't find any way to convert the struct array to an NSMuteableArray or something similar I can store. The only idea until now is to go through each entry and copy it directly to a new array or to use much or objective-c code all over the project, so i never need to convert from swift arrays to objective-c arrays. Both are things I don't want to do.
推荐答案
Swift 结构不是类,因此它们不符合 AnyObject
协议.你必须重新考虑你的方法.以下是一些建议:
Swift structs are not classes, therefore they don't conform to AnyObject
protocol. You have to rethink your approach. Here are some suggestions:
将您的
struct
转换为final class
以强制执行不变性
Convert your
struct
tofinal class
to enforce immutability
final class MyStruct {
let start : NSDate = NSDate()
let stop : NSDate = NSDate()
}
encoder.encodeObject(mystructs)
将它们映射为 [String: NSDate]
let structDicts = mystructs.map { ["start": $0.start, "stop": $0.stop] }
encoder.encodeObject(structDicts)
这篇关于使用 Swift 将类中的结构保存到 NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Swift 将类中的结构保存到 NSUserDefaults
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01