我將數組保存到模型中時,保存數據時未包含可選(...),但是當讀取數據時我得到可選(...)環繞它。感謝您的幫助和耐心,因爲我是Swift新手。在Swift中可選包裝,爲什麼Swift將「可選」添加到字符串
這是println
添加值模型時:
saveOperativesInModel: Test Name
這是println
讀取值時,從模型回:
getOperativesFromModel: Optional(Test Name)
爲什麼雨燕添加「可選(xxx)「到字符串?
這是降低代碼:
func saveOperativesInModel() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("Operatives", inManagedObjectContext: managedContext)
var item: NSManagedObject!
if let operativesList = self.operativesResult?.operativesList {
self.operativesTable.removeAll()
for itemInArray in operativesList {
item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
item.setValue(itemInArray.firstName, forKey: "firstName")
var error: NSError?
if !managedContext.save(&error) {
} else {
self.operativesTable.append(item!)
println("saveOperativesInModel: \(itemInArray.firstName)")
}
}
}
let fetchRequest1: NSFetchRequest! = NSFetchRequest(entityName:"Operatives")
let fetchedResults = managedContext.executeFetchRequest(fetchRequest1, error: &error) as? [NSManagedObject]
if let operativesTable = fetchedResults {
if operativesTable.count > 0 {
for item in operativesTable {
let operative: Operative! = Operative()
operative.firstName = String (stringInterpolationSegment: item.valueForKey("firstName"))
println("getOperativesFromModel: \(operative.firstName)")
}
}
}
}
感謝(和刪除以往的評論:)那麼,什麼是解決方案?我應該用避免Optional()的方式來包裝它,因爲當我把這個數組放到TableView中時,我也得到Optional() –
請參閱我對我的文章所作的編輯。 – aaplmath