我有问题想弄清楚如何使用NSUserDefaults保存我的“RiskEntry”类型的字符串。我已经通过其他一些帖子,但不知何故,我仍然无法解决这个问题。使用NSUserDefaults和结构类型数组
让我来解释一下下面的代码吧:我在下面的代码片段中从我的类CustomCell中获取一些数据。在这里,我首先检查一个“标识符”要更新哪个数组,使用新的数组值“结果”。
它一切正常,更新后的数组存储在riskEntry中。 但是,我现在无法解决如何使用NSUserDefaults进行存储。当我尝试用例如riskItemDefaults.set(riskEntry, forKey: "riskItem")
我收到一个异常错误。
任何想法我在做什么错在这里?
SWIFT3(我删除了这个问题不相关的所有代码)
class: RiskPlan: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomCellUpdaterDelegate {
var riskEntry = [RiskEntry]()
var riskItemDefaults = UserDefaults.standard
// ------ start of delegate function (receiving from CustomCell) ---------
func transferData(consequencesTranferred: String, identifier: String) {
if let index = riskEntry.index(where: {$0.title as String == identifier}) {
riskEntry[index].consequences = consequencesTranferred
} else {
print ("nothing")
}
// save with NSUserDefaults
riskItemDefaults.set(riskEntry, forKey: "riskItem")
}
}
这是我的结构:
public struct RiskEntry {
let title: String
var consequences: String
}
我自定单元
// ---------------- delegate to transfer entered data to VC -----------------
protocol CustomCellUpdaterDelegate {
func transferData(consequencesTranferred: String, identifier: String)
}
// ---------------- start of class CellCustomized -----------------
class CustomCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate, UITextViewDelegate {
var delegate: CustomCellUpdaterDelegate?
// text fields, text views and picker views
@IBOutlet weak var riskTitle: UITextView!
@IBOutlet weak var consequences: UITextView!
// ---------------- listener for text view to save input in string when editing is finished -----------------
func textViewDidEndEditing(_ textView: UITextView) {
if textView.tag == 1 {
textConsequences = consequences.text
nameIdentifier = riskTitle.text
delegate?.transferData(consequencesTranferred: self.textConsequences, identifier: nameIdentifier)
} else {
print ("nothing")
}
}
}
你收到的例外是什么? –
我的控制台输出是:'libC++ abi.dylib:以'NSException类型的未捕获异常终止,而我的AppDelegate.swift类被选为'线程1:信号SIGABRT' – Jake2Finn
可能的http://stackoverflow.com/重复问题/ 38406457 /如何保存一个自定义数组结构到nsuserdefault-with-swift?rq = 1 – hotpaw2