使用 Swift 将类中的结构保存到 NSUserDefaults

Save struct in class to NSUserDefaults using Swift(使用 Swift 将类中的结构保存到 NSUserDefaults)

本文介绍了使用 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:

  1. 将您的 struct 转换为 final class 以强制执行不变性

  1. Convert your struct to final 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

    基础教程推荐