我正在尝试扩展我在UserDefaults中保存的数组。我有2个视图,在第一个视图中我声明了包含3个主题的数组,然后我将其保存在UserDefaults中。在第二个视图中我可以打印它们,但是当我尝试使用UITextView中的新主题扩展我的数组时,我收到错误消息
Thread1:EXC_BAD_INSTRUCTION(代码= EXC_l386_INVOP,子代码= 0x0)
我做错了什么?
class ViewController: UIViewController {
@IBOutlet weak var text: UITextView!
var array: [String] = ["Prvni", "Druhy"]
var prvni = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func zapsat(_ sender: UIButton) {
prvni = text.text!
array.insert(prvni, at: 2)
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "KEY")
defaults.synchronize()
}
@IBAction func vypsat(_ sender: UIButton) {
if((UserDefaults.standard.array(forKey: "KEY")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
print(historyWords)
}
}
}
和第二个viewcontroller
class druhy: UIViewController {
var array = [String]()
var druhy = ""
@IBOutlet weak var text: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func vypsat(_ sender: UIButton) {
if((UserDefaults.standard.array(forKey: "KEY")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
print(historyWords)
}
}
@IBAction func zapsat(_ sender: UIButton) {
druhy = text.text!
if((UserDefaults.standard.array(forKey: "KEY")) != nil){
var array = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
print(array)
}
array.insert(druhy, at: 3)
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "KEY")
defaults.synchronize()
}
}
答案 0 :(得分:0)
在此代码中从数组中删除var
声明以使用全局数组
var array = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
到
array = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
然后使用append
而不是insertarray.append(druhy)
总代码 -
druhy = text.text!
if((UserDefaults.standard.array(forKey: "KEY")) != nil){
array = (UserDefaults.standard.array(forKey: "KEY") as? [String])!
print(array)
}
array.append(druhy,)
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "KEY")
defaults.synchronize()