将 Swift 数组转换为 NSData 用于 NSUserDefaults.StandardUserDefaults 持久存储

Converting Swift Array to NSData for NSUserDefaults.StandardUserDefaults persistent storage(将 Swift 数组转换为 NSData 用于 NSUserDefaults.StandardUserDefaults 持久存储)

本文介绍了将 Swift 数组转换为 NSData 用于 NSUserDefaults.StandardUserDefaults 持久存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过制作一个小型应用程序来了解 Swift(在对 Obj-C 相对胜任之后).我想使用 NSUserDefaults 来持久保存少量数据,但我遇到了问题.

I'm trying to get my head around Swift (after being relatively competent with Obj-C) by making a small app. I would like to use NSUserDefaults to persistently save a small amount of data but I am having problems.

我像这样初始化一个空的元组数组:

I initialise an empty array of tuples like this:

var costCategoryArray: [(name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float)]=[]

当数组有条目时,我想使用标准 Swift 代码将数组保存到 NSUserDefaults,例如:

When the array has an entry, I want to save the array to NSUserDefaults with standard Swift code such as this:

NSUserDefaults.standardUserDefaults().setObject(costCategoryArray, forKey: "financialData")
NSUserDefaults.standardUserDefaults().synchronize()

我收到一条错误消息,指出元组数组不符合 AnyObject 类.于是我试着把它变成了NSData:

I get an error saying that the tuple array doesn't conform to the AnyObject class. So I tried to turn it into NSData:

var myNSData: NSData = NSKeyedArchiver.archivedDataWithRootObject(costCategoryArray)
var myUnarchivedData: Array = NSKeyedUnarchiver.unarchiveObjectWithData(myNSData)

...但是在转换为 NSData 的过程中我遇到了同样的错误.我的数组持有的对象不符合 AnyObject.我还尝试在每个阶段使用以下方法使其不可变:

...but I get the same error during the conversion to NSData. The object being held by my array doesn't conform to AnyObject. I've also tried at each stage to make it immutable by using:

let immutableArray = costCategoryArray

我也尝试过创建一个类而不是使用我理解的元组,这会使其符合 AnyObject:

Ive also tried creating a class instead of using tuples which I understood would make it comply with AnyObject:

class costCategory : NSObject {
    var name : String
    var defaultValue : Int
    var thisMonthsEstimate : Int
    var sumOfThisMonthsActuals : Int
    var riskFactor : Float
    var monthlyAverage : Float


    init (name:String, defaultValue:Int, thisMonthsEstimate:Int,     sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float) {
        self.name = name
        self.defaultValue = defaultValue
        self.thisMonthsEstimate = thisMonthsEstimate
        self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
        self.riskFactor = riskFactor
        self.monthlyAverage = monthlyAverage
    }
}

但新的错误是:

属性列表格式无效:200(属性列表不能包含'CFType'类型的对象)"

"Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')"

元组数组有什么问题?为什么我不能存储类对象数组?我觉得我需要一些专家的建议,因为到目前为止我尝试用 Swift 做的所有事情都几乎不兼容......

What is the problem with an array of tuples? Why can't I store an array of class objects? I feel like I need some expert advice as so far everything I try to do with Swift is pretty much incompatible...

谢谢!

推荐答案

你归档到 NSData 并返回的任何东西都需要实现 NSCoding 协议.此外,我发现我的 Swift 类必须扩展 NSObject.下面是一个编码和解码的 Swift 类的简单示例:

Anything you are archiving to NSData and back needs to implement the NSCoding protocol. I found that in addition, my Swift class had to extend NSObject. Here is a quick example of a Swift class that encodes and decodes:

class B : NSObject, NSCoding {
    var str : String = "test"

    required init(coder aDecoder: NSCoder) {
        str = aDecoder.decodeObjectForKey("str") as String
    }

    override init() {
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(str, forKey: "str")
    }
}

// create an Object of Class B
var b : B = B()

// Archive it to NSData
var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(b)

// Create a new object of Class B from the data
var b2 : B = NSKeyedUnarchiver.unarchiveObjectWithData(data) as B

这篇关于将 Swift 数组转换为 NSData 用于 NSUserDefaults.StandardUserDefaults 持久存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将 Swift 数组转换为 NSData 用于 NSUserDefaults.StandardUserDefaults 持久存储

基础教程推荐