2017-08-04 62 views
0

我保存的值從一個TextView到coredata像這樣斯威夫特3可選被附加到字符串

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」)或零,如果它是空的

我不明白爲什麼我想要的值是可選的

回答

0

替換此行:

let attribute_name = textView.text 

與此:

let attribute_name = textView.text ?? "" 

應該解決這個問題可選。如果仍然不工作,然後替換此行還有:我在哪裏使用

let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name") ?? "") 
+0

最後一行工作 –

2

它是因爲var將被聲明爲可選。 使用此代碼訪問變量的值。

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

let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name")) 

用?因爲我不斷獲得條件綁定的初始化器必須具有可選類型,而不是'字符串'錯誤 –