从 UItextfield 到 double 值的值并保存到核心数据

Value from UItextfield to double value and save to core data

我试图在我的 table 视图控制器中显示一个双精度值。我通过文本 field.one 从用户那里获取值,输入是字符串,另一个是 double.I 将其存储在核心数据中。我使用 NSfetchRequest 将其显示到 table 视图。 table 视图单元格有 2 个标签,其中包含字符串和双精度数。当我 运行 时,在 table 视图中只能看到字符串值,而不是双精度值。我该如何解决这个问题

> Blockquote
      override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let Cell : TableViewCellFixed = tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCellFixed

        let data : NSManagedObject = List[indexPath.row] as! NSManagedObject
         //cellName and cellPrice are UILabels

        Cell.cellName.text = data.valueForKey("name") as? String

        Cell.cellPrice.text = data.valueForKey("price") as? String



        return Cell
    }

p.s :我尝试将 Cell.cellPrice.text = data.valueforkey("price") 作为 Double 并给出错误:无法将 double 分配给 String

Blockquote // add to core data

@IBAction func AddSave(sender: UIButton) {
    let appDel :AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let theContext : NSManagedObjectContext = appDel.managedObjectContext
    let theEnt = NSEntityDescription.entityForName("Entity", inManagedObjectContext: theContext)

    let newItem = Model(entity : theEnt!,insertIntoManagedObjectContext: theContext)

    newItem.name = addName.text!
    let num :Double = (addPrice.text! as NSString).doubleValue
    newItem.price = num  
    do
    {
       try theContext.save()
    }
    catch {

    }

    print("name \(newItem.name)")
    print ("price \(newItem.price)")
    print ("double \(num)")


    self.navigationController?.popViewControllerAnimated(true)
}

在控制台中输出是 名称格莱美 价格 6.9466761353417e-310 双 600.0

像这样更改您的代码

coredata

中存储双精度值
let num :Double = (addPrice.text! as NSString).doubleValue
let price = NSNumber(double: num)
ewItem.price = price  

coredata

中检索双精度值
 if let price = (data.valueForKey("price"))?.doubleValue {
     cell.cellPrice.text = "\(price)"
}
else {
     cell.cellPrice.text = 0
}

希望对您有所帮助。

Cell.cellPrice.text = "\(date.valueForKey("price"))"

试试这个

 > Blockquote
          override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let Cell : TableViewCellFixed = tableView.dequeueReusableCellWithIdentifier("cell") as! TableViewCellFixed

        let data : NSManagedObject = List[indexPath.row] as! NSManagedObject
         //cellName and cellPrice are UILabels

        Cell.cellName.text = data.valueForKey("name") as? String
        let price = data.valueForKey("price")
        Cell.cellPrice.text = "\(price)" 



        return Cell
    }