Ios Swift 3可选被附加到字符串
我将一个值从textview保存到coredata,如下所示Ios Swift 3可选被附加到字符串,ios,core-data,swift3,Ios,Core Data,Swift3,我将一个值从textview保存到coredata,如下所示 let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let newAttr = NSEntityDescription.insertNewObject(forEntityName: "TableName", into: context ) le
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
出于某种原因,每次输出都是可选的(“originalTextValue”),如果为空,则为nil
我不明白为什么我想要的值被可选的Its包围,因为var将被声明为可选的。 使用此代码访问变量的值
if let value = originalTextValue{
//use value here now it wont be optional.
print(value)
}
这是因为var将被声明为可选的。 使用此代码访问变量的值
if let value = originalTextValue{
//use value here now it wont be optional.
print(value)
}
替换此行:
let attribute_name = textView.text
为此:
let attribute_name = textView.text ?? ""
它应该解决这个可选问题。如果仍不起作用,则也应更换此线路:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
与:
替换此行:
let attribute_name = textView.text
为此:
let attribute_name = textView.text ?? ""
它应该解决这个可选问题。如果仍不起作用,则也应更换此线路:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
与:
我在哪里使用它?因为我一直在获取条件绑定的初始值设定项必须具有可选类型,而不是“string”错误我在哪里使用它?因为我一直在获取条件绑定的初始值设定项必须具有可选类型,而不是“字符串”错误