Search code examples
iosstringswiftnsnumber

Swift with core data


i am just starting out with swift and core data. I have an entity invoiceList and created some attributes (some strings, integer 32 and decimal).

I created an edit/add viewcontroller, but now i am stuck with the add newItem part. I am getting the error "cannot assign a value of type string? to a value of type NSNumber?"

I have tried different ways to cast vat textfield as Int but without success.

I tried

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

here the newItem func

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?

}

Now i know invoiceVAT is a core data attribute with type decimal and vat is a textfield. How can i fix this?


Solution

  • Here's a quick example of using a number formatter to retrieve an NSNumber from a String

    let aNumberString = "1235.45"
    
    let numberFormatter = NSNumberFormatter()
    
    if let theNumber = numberFormatter.numberFromString(aNumberString) {
    
    println(theNumber)
    }