gpt4 book ai didi

Swift:无法在 NSUserDefaults 中保存具有更多记录的元组

转载 作者:行者123 更新时间:2023-11-28 06:56:49 25 4
gpt4 key购买 nike

我正在尝试将元组存储在 NSUserDefaults 中。我的元组在下面。

var primaryNumberAndName: [(name:String , number: String, numberType: String, imageProfile: UIImage, imageLogo: UIImage)] = []

向元组添加数据

for (var i : Int = 0; i < primaryNameArr.count; i++)
{
primaryNumberAndName.append(name: primaryNameArr[i] as! String,
number: primaryNumberArr[i] as! String,
numberType: primaryNumberTypeArr[i] as! String,
imageProfile: UIImage(named: "profile_man.png")!,
imageLogo: UIImage(named: "Our_Logo.png")!)

}

编码:

var dictOfObjectsData = NSKeyedArchiver.archivedDataWithRootObject(primaryNumberAndName)
myUserDefaul.setObject(dictOfObjectsData, forKey: "PrimaryContacts")

错误:

Cannot invoke 'archivedDataWithRootObject' with an argument list of type {[(name:String , number: String, numberType: String, imageProfile: UIImage, imageLogo: UIImage)]}

请指导我如何解决这个问题。

最佳答案

一种选择是在保存之前将 tuple 转换为 Dictionary。像这样:

let primaryNumberKey = "primaryNumber"
let nameKey = "name"

func serializeTuple(tuple: AccessTuple) -> myDictionary {
return [
primaryNumberKey : tuple.primaryNumber,
nameKey : tuple.name
]
}

func deserializeDictionary(dictionary: myDictionary) -> myTuple {
return myTuple (
dictionary[primaryNumberKey] as String!,
dictionary[nameKey] as String!
)
}

这是你如何使用它:

// Writing to defaults
let myConvertedDictionary = serializeTuple(myTuple)
NSUserDefaults.standardUserDefaults().setObject(myConvertedDictionary, forKey: "UserDetailslKey")

// Reading from defaults
let myFetchedDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey("UserDetailslKey") as myDictionary
let myFetchedTuple = deserializeDictionary(myFetchedDictionary)

您现在可以按常规方式存档字典!

关于Swift:无法在 NSUserDefaults 中保存具有更多记录的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33348007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com