【问题标题】:Swift 3 Optional being appended to StringSwift 3 Optional 被附加到 String
【发布时间】:2018-01-11 19:31:02
【问题描述】:

我像这样将文本视图中的值保存到核心数据

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,如果它是空的

我不明白为什么我想要的值被可选

【问题讨论】:

    标签: ios core-data swift3


    【解决方案1】:

    这是因为 var 将被声明为可选。 使用此代码访问变量的值。

    if let value = originalTextValue{
     //use value here now it wont be optional.
     print(value)
    }
    

    【讨论】:

    • 我在哪里使用它?因为我不断获取条件绑定的初始化程序必须具有可选类型,而不是“字符串”错误
    【解决方案2】:

    替换这一行:

    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") ?? "")
    

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      相关资源
      最近更新 更多