在NSUserDefaults中保存一个元组 [英] Save a tuple in NSUserDefaults

查看:131
本文介绍了在NSUserDefaults中保存一个元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个元组来存储这样的东西。

I'm using a tuple to store something like this.

var accessLavels: (hasInventoryAccess: Bool, hasPayrolAccess: Bool)
accessLavels = (hasInventoryAccess: true, hasPayrolAccess: false)

现在我要保存它在 NSUserDefaults的

NSUserDefaults.standardUserDefaults().setValue(accessLavels, forKey: "AccessLevelKey")
NSUserDefaults.standardUserDefaults().synchronize()

但是我收到以下错误。

类型'(hasInventoryAccess:Bool,hasPayrolAccess:Bool)'不符合协议'AnyObject'

如何解决此问题?如果它不可能,那么欢迎保存元组的任何其他建议。

How can I resolve this issue? If its impossible, then any other suggestions to save a tuple is welcome.

谢谢。

推荐答案

我遇到了类似的场景,尝试使用 NSCoder 对元组进行编码。我解决它的方法是手动将元组转换为字典。这不是一个很好的解决方案,因为如果元组发生变化,需要在几个地方更改密钥。

I encountered a similar scenario trying to encode a tuple with NSCoder. The way I am solving it is by manually converting the tuple to a Dictionary. This is not a great solution as the keys need to be changed in several places if the tuple ever changes.

我的元组中有一个嵌套的枚举,并给它一个基本类型(String),我从中转换了原始值。这是一个额外的工作,但幸运的是你的只是原始人。

I had a nested enum in my tuple and gave it a base type (String) from which I converted the raw value. It was a little extra work but thankfully yours is only primitives.

# SerializeableTuple.swift

typealias AccessTuple = (hasInventoryAccess: Bool, hasPayrolAccess: Bool)
typealias AccessDictionary = [String: Bool]

let InventoryKey = "hasInventoryAccess"
let PayrollKey = "hasPayrollAccess"

func serializeTuple(tuple: AccessTuple) -> AccessDictionary {
    return [
        InventoryKey : tuple.hasInventoryAccess,
        PayrollKey : tuple.hasPayrolAccess
    ]
}

func deserializeDictionary(dictionary: AccessDictionary) -> AccessTuple {
    return AccessTuple(
        dictionary[InventoryKey] as Bool!,
        dictionary[PayrollKey] as Bool!
    )
}







# Encoding / Decoding

var accessLavels: AccessTuple = (hasInventoryAccess: true, hasPayrolAccess: false)

// Writing to defaults
let accessLevelDictionary = serializeTuple(accessLavels)
NSUserDefaults.standardUserDefaults().setObject(accessLevelDictionary, forKey: "AccessLevelKey")

// Reading from defaults
let accessDic = NSUserDefaults.standardUserDefaults().dictionaryForKey("AccessLevelKey") as AccessDictionary
let accessLev = deserializeDictionary(accessDic)

这篇关于在NSUserDefaults中保存一个元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆