ios (Swift) 将数组存储和检索到 NSUserDefaults
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30118735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Swift) Storing and retrieving Array to NSUserDefaults
提问by William Larson
I am trying to store an array to NSUserDefaults
and retrieve the array when needed to populate a UITableView
.
我正在尝试将数组存储到NSUserDefaults
并在需要填充UITableView
.
Currently I am using:
目前我正在使用:
//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
NSUserDefaults.standardUserDefaults().synchronize()
//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()
But I get
但我得到
fatal error: unexpectedly found
nil
while unwrapping an Optional value
致命错误:
nil
在解开可选值时意外发现
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
尝试加载数据时。我不确定问题出在存储还是检索中。有没有人经历过这个?
回答by Vivek Molkar
From your code I see you are storing some array
从你的代码我看到你正在存储一些数组
// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
并检索字符串
//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
可能存在类型不匹配,您存储一种类型并检索另一种类型。
While retrieving either use arrayForKey()
or objectForKey()
see the code below.
在检索时使用arrayForKey()
或objectForKey()
查看下面的代码。
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
或者
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
如果它是一个数组,我会选择第一个。
回答by Jatin Patel - JP
Here are the way that you can store and retrieved array of object with help of NSKeyArchive
.
以下是您可以在 的帮助下存储和检索对象数组的方法NSKeyArchive
。
To Store array to NSUserDefault.
将数组存储到 NSUserDefault。
let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")
To Retrieved array from NSUserDefault.
从 NSUserDefault 检索数组。
let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
print(placesArray)
}
Hope this help you.
希望这对你有帮助。
回答by Suragch
Saving and Retrieving a String array to UserDefaults
将字符串数组保存和检索到 UserDefaults
Save array
保存数组
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
检索数组
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()
See more at How to save user settings using NSUserDefaults
回答by RyanOfCourse
What are you storing in the array?
你在数组中存储什么?
If it's objects it won't work, if It's just strings or numbers then it should be fine.
如果它是对象,它将不起作用,如果它只是字符串或数字,那么它应该没问题。
Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.
您接下来应该采取的步骤应该是打开异常断点,可能还有 println() 一切可能,以便您可以查明问题的确切位置。
As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil
作为在黑暗中的一个镜头,我建议也许 (identity.text!) 出现为零
Also you should probably change it to this
你也应该把它改成这个
if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){
myArray = [tabledata!]
tableView.reloadData()
}
This will make the code not even try to run unless there is a value it can use
这将使代码甚至不会尝试运行,除非有它可以使用的值
回答by Gangireddy Rami Reddy
Latest swift3 version to store array of data into userdefaults and get that array of data using keys
最新的 swift3 版本将数据数组存储到用户默认值中并使用键获取该数据数组
let nameArray = ["Ramu","JAGAN","Steve","Swift"]
let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
UserDefaults.standard.set(namesArrayData, forKey: "arrayData")
RetriveData
检索数据
let retriveArrayData= UserDefaults.standard.object(forKey: "arrayData") as? NSData
if let retriveArrayData= namesArrayData{
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
print(retriveArray )
}
回答by flame3
This has been changed in swift 3. Note that this works with device but not playground or simulator
这已在 swift 3 中更改。请注意,这适用于设备,但不适用于操场或模拟器
//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "history")
defaults.synchronize()
//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
print(historyWords)
}
回答by Mr.Javed Multani
Store into User Default:
存储到用户默认值:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Retrieving array from User Defaults:
从用户默认值中检索数组:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}