gpt4 book ai didi

ios - 无法快速将 NSMutableArray 的值存储在 NSUserdefault 中

转载 作者:行者123 更新时间:2023-11-28 08:45:15 39 4
gpt4 key购买 nike

您好,我有一个 NSMutablearray,我正在尝试将此数组存储在 NSUserdefault 中,但在存储它时出现错误。

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

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

无法将类型 '[(name: String, id: String)]' 的值转换为预期的参数类型 'AnyObject?

谢谢 :)

最佳答案

我在 Playground 上进行了一些测试,想出了一个可能的解决方案。基本上,我们将 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")
}

希望对你有帮助!

关于ios - 无法快速将 NSMutableArray 的值存储在 NSUserdefault 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505182/

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