简体   繁体   English

swift无法在NSUserdefault中存储NSMutableArray的值

[英]Can't store value of NSMutableArray in NSUserdefault in swift

Hi I have a NSMutablearray and i am trying to store this array in NSUserdefault but I am getting error while storing it. 嗨,我有一个NSMutablearray ,我试图将此数组存储在NSUserdefault但是在存储它时出现错误。

var mutableArray: [(name: String, id: String)] = []

NSUserDefaults.standardUserDefaults().setObject(mutableArray, forKey: "arrayKey")

Cannot convert value of type '[(name: String, id: String)] ' to expected argument type 'AnyObject? 无法将类型'[(name: String, id: String)] '的值转换为预期的参数类型'AnyObject? .

Thanx :) 谢谢:)

I have come up with a possible solution with some testing in a playground. 我已经提出了可能的解决方案,并在操场上进行了一些测试。 Basically, we convert the NSMutableArray to a standard array, then to a string, then we neaten up the string, then we store it in NSUserDefaults. 基本上,我们将NSMutableArray转换为标准数组,然后转换为字符串,然后整理字符串,然后将其存储在NSUserDefaults中。 Later, we access it from NSUserDefaults, convert it to a standard array, then finally convert it back to the very same NSMutableArray. 稍后,我们从NSUserDefaults访问它,将其转换为标准数组,最后将其转换回完全相同的NSMutableArray。 Here goes the code... 代码在这里...

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")
}

I hope this helps you! 我希望这可以帮助你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM