您好我有一个NSMutablearray
,我正在尝试将此数组存储在NSUserdefault
中,但我在存储时遇到错误。
var mutableArray: [(name: String, id: String)] = []
NSUserDefaults.standardUserDefaults().setObject(mutableArray, forKey: "arrayKey")
无法转换'[(name: String, id: String)]
类型的值'预期参数类型'AnyObject?
。
Thanx:)
答案 0 :(得分:0)
我想出了一个可能的解决方案,在操场上进行一些测试。基本上,我们将NSMutableArray转换为标准数组,然后转换为字符串,然后我们将字符串连接起来,然后将它存储在NSUserDefaults中。稍后,我们从NSUserDefaults访问它,将其转换为标准数组,然后最终将其转换回相同的NSMutableArray。这里是代码...
var mutarray:NSMutableArray = ["yo", "oy", "pppppp", "01", "long: on", "off"] // just some sample NSMutableArray, replace this with your actual NSMutableArray
var arraytoarray = mutarray as NSArray as! [String] // We convert that NSMutableArray to a standard array of strings
var arraystring = String(arraytoarray) // we convert that standard array to one long string
// then, below, we optimize it and remove characters that will mess up your process later (this might take some tinkering based on your array, but I don't think so)
arraystring = arraystring.stringByReplacingOccurrencesOfString("\"", withString: "")
arraystring = arraystring.stringByReplacingOccurrencesOfString("[", withString: "")
arraystring = arraystring.stringByReplacingOccurrencesOfString("]", withString: "")
arraystring = arraystring.stringByReplacingOccurrencesOfString(" ", withString: "")
// then we create an NSUserDefault of that string we've created
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("arraystring", forKey: "stringkey")
// then later on we read that string and create the variable 'name' for it.
if let name = defaults.stringForKey("stringkey") {
print(name)
// we then convert it to an array again
let fullNameArr = name.characters.split{$0 == ","}.map(String.init)
print(fullNameArr)
// and finally back to an NSMutableArray (if necessary)
var nsMutableArray = NSMutableArray(array: fullNameArr)
} else {
// this is triggered if NSUserDefault was not saved above, in error.
print("nope")
}
我希望这可以帮到你!