【问题标题】:Can't store value of NSMutableArray in NSUserdefault in swift无法将 NSMutableArray 的值快速存储在 NSUserdefault 中
【发布时间】:2016-02-19 12:17:21
【问题描述】:

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

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

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

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

感谢:)

【问题讨论】:

  • 您不能将元组存储在 NSUserDefaults 中,只能存储符合 NSObject 的对象。
  • 谢谢@EricD。有没有其他方法可以解决这个问题。
  • Save a tuple in NSUserDefaults 的可能重复 :)
  • 您可以将您的阵列存档到 nsdata 并保存。这是 obj-c 中的一个示例:stackoverflow.com/questions/6696558/…
  • @user3820661 这不是 NSMutableArray。这是一个 Swift 原生的元组数组。

标签: ios swift nsmutablearray nsuserdefaults nsmutabledictionary


【解决方案1】:

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

希望对你有帮助!

【讨论】:

  • 嘿@user3820661 如果这对你有帮助,请告诉我!!
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2015-07-05
相关资源
最近更新 更多