yukti yukti - 3 months ago 13x
iOS Question

Value from UItextfield to double value and save to core data

I am trying to display a value which is a double in my table view controller. I get the value from a user through a text field.one input is string and another is a double.I store it in the core data. I used the NSfetchRequest to display it to the table view. The table view cell has 2 labels into which the string and double go. When I run only the string values are seen in the table view not the double. How do I fix this

> 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 :I tried Cell.cellPrice.text = data.valueforkey("price") as Double and it gives an error : Cannot assign double to String

// 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
try theContext.save()
catch {


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


in the console the output is
name Grammy
price 6.9466761353417e-310
double 600.0


Change your code like this

To Store double in coredata

let num :Double = (addPrice.text! as NSString).doubleValue
let price = NSNumber(double: num)
newItem.price = price  

Retrieve double value from coredata

let num = NSNumber(double: data.valueForKey("price") as! Double)
cell.cellPrice.text = String(format: "%f",num.doubleValue)

Hope this will help you.