Save a tuple in NSUserDefaults(在 NSUserDefaults 中保存一个元组)
问题描述
我正在使用一个元组来存储这样的东西.
I'm using a tuple to store something like this.
var accessLavels: (hasInventoryAccess: Bool, hasPayrolAccess: Bool)
accessLavels = (hasInventoryAccess: true, hasPayrolAccess: false)
现在我想将它保存在 NSUserDefaults
中.
Now I want to save it in 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
对元组进行编码时遇到了类似的情况.我解决它的方法是将元组手动转换为 Dictionary
.这不是一个很好的解决方案,因为如果元组发生更改,则需要在多个位置更改键.
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.
我的元组中有一个嵌套枚举,并给了它一个基本类型(字符串),我从中转换了原始值.这是一些额外的工作,但谢天谢地,你的只是原语.
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 中保存一个元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 NSUserDefaults 中保存一个元组
基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01