我刚刚开始使用swift和核心数据。我有一个实体invoiceList并创建了一些属性(一些字符串、整数32和十进制)。
我创建了一个edit/add viewcontroller,但是现在我被add newItem部分困住了。我得到的错误是“无法分配字符串类型的值?”?“设置为NSNumber类型的值?”
我尝试了不同的方法将vat textfield转换为Int,但没有成功。
我试过了

    var invoiceVATString = nItem.valueForkey("invoiceVAT") as String
    invoiceVATString = vat.text

这里是newItem函数
func newItem(){
    let context = self.context
    let ent = NSEntityDescription.entityForName("invoiceList", inManagedObjectContext: context)

    let nItem = InvoicesList(entity: ent!, insertIntoManagedObjectContext: context)

    nItem.invoiceShopName = shopName.text
    nItem.invoiceDescr = productDescription.text
    nItem.invoiceVAT = vat.text<-cannot assign a value of type string? to a value of type NSNumber?
    nItem.invoiceNumber = orderNumber.text<-cannot assign a value of type string? to a value of type NSNumber?

}

现在我知道invoiceVAT是decimal类型的核心数据属性,而vat是一个文本字段。我该怎么解决?

最佳答案

下面是一个使用数字格式化程序从字符串中检索NSNumber的快速示例

let aNumberString = "1235.45"

let numberFormatter = NSNumberFormatter()

if let theNumber = numberFormatter.numberFromString(aNumberString) {

println(theNumber)
}

08-16 14:24