从UItextfield值加倍值并保存到核心数据
我想显示一个值,这是我的表视图控制器中的一个双。我通过文本字段获取用户的值。一个输入是字符串,另一个是double。我将它存储在核心数据中。我使用NSfetchRequest将其显示到表视图。表格视图单元格有两个标签,字符串和双精度值都放在该标签中。当我只运行字符串值在表视图中看到不是双。如何解决这个从UItextfield值加倍值并保存到核心数据
> 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
}
PS:我想Cell.cellPrice.text = data.valueforkey( “价格”)为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
}
希望这将帮助你存储双检索双重价值。
是的,它确实非常感谢你。虽然它显示为零,而不是使用输入的值。我通过文本框从用户那里获得vlaue。为了将它保存到double类型的核心数据属性中,我不得不将它转换为double类型。我这样做newItem.price =(addPrice.text!作为NSString).doubleValue 为什么它变成零?是因为铸造吗?感谢您的回答 – yukti
我编辑了我的答案检查 –
它说错误:缺少语言环境。我在data.valueforkey之前添加了如下所示的语言环境:Cell.cellPrice.text = NSString(format:“%f”,locale:data.valueForKey(“price”)as!字符串,并且仍然显示错误,说明不能隐藏anyObeject到NS语言环境类型 – yukti
Cell.cellPrice.text = “\(date.valueForKey(” 价格 “))”
它解决了错误,但在显示时显示(“%ld”,无)在我的表格视图中。谢谢你的回答 – yukti
如果你想要做一些数学你可以设置一个双变量对于试试这个
> 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
}
..如果你想显示双精度值,你必须把它作为字符串。 label.text仅限accpet字符串。 –