【发布时间】:2016-10-15 18:41:38
【问题描述】:
我很难弄清楚如何使用 NSUserDefaults 保存“RiskEntry”类型的字符串。我已经浏览了其他一些帖子,但不知何故我仍然没有设法解决这个特定问题。
让我解释一下下面的代码现在做了什么:我在下面的代码 sn-p 中从我的类 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: terminating with uncaught exception of type NSException而我的 AppDelegate.swift 类被选为Thread 1: signal SIGABRT -
这个解决方案做到了!不过,我必须将其转换为 swift 3 并对其进行修改以适合我的用例。我会将其作为答案发布,以防将来对其他人有所帮助:-)
标签: ios arrays swift struct nsuserdefaults