我将textview中的值保存到像这样的coredata
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newAttr = NSEntityDescription.insertNewObject(forEntityName: "TableName", into: context )
let attribute_name = textView.text
newAttr.setValue(attribute_name, forKey "attr_name")
context.save()
然后我试着像这样读回来:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest = TableName.fetchRequest()
let cdRowsArr = try context.fetch(fetchRequest)
let cdRow = cdRows[0]
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
let attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize:15)]
let boldString = NSMutableAttributedStrign(string: txtViewDesc, attributes: attrs)
textView.attributedText = boldString
由于某种原因,每次输出都是Optional(“originalTextValue”)或nil,如果它是空的
我不明白为什么我想要的值被可选的
包围答案 0 :(得分:2)
因为var将被声明为可选。 使用此代码来获取变量的访问值。
if let value = originalTextValue{
//use value here now it wont be optional.
print(value)
}
答案 1 :(得分:0)
替换此行:
let attribute_name = textView.text
用这个:
let attribute_name = textView.text ?? ""
它应该解决这个可选问题。如果它仍然不起作用,那么也替换这一行:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
使用:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name") ?? "")