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

时间:2015-10-26 14:17:14

标签: swift nsuserdefaults nskeyedarchiver

我正在尝试将元组存储在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)]}

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

1 个答案:

答案 0 :(得分:1)

一种选择可能是在保存之前将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)

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