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

时间:2016-06-28 07:12:46

标签: ios uilabel

我正在尝试在表视图控制器中显示一个双精度值。我通过文本字段从用户获取值。一个输入是字符串而另一个是double。我将它存储在核心数据中。我使用NSfetchRequest将其显示到表视图中。表格视图单元格有2个标签,字符串和双精度表。当我只运行字符串值时,在表视图中看不到双精度值。我该如何解决这个

> 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

  

块引用   //添加到核心数据

@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

3 个答案:

答案 0 :(得分: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
}

希望这会对你有所帮助。

答案 1 :(得分:0)

Cell.cellPrice.text =“\(date.valueForKey(”price“))”

答案 2 :(得分:0)

试试这个

 > 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
    }