return CoreDat - Swift

0

I am not able to assign a textField with the result of a search when it is int, with String sure

 var results:NSArray =  try context.executeFetchRequest(request) as! [NSManagedObject]

        if(results.count > 0){
            var res = results[0] as! NSManagedObject

            nomeText.text = res.valueForKey("nome") as? String
            idadeText.text = res.valueForKey("idade") as? String
               print(res.valueForKey("idade") as? String)
            }

In print it returns me nil .. when it changes to Int, it returns me correct value .. how do I assign the textField to this value, remembering that with the name field I do not have this error

    
asked by anonymous 23.10.2015 / 14:16

2 answers

1

The syntax "as?" returns nil if it can not cast, and in this case the value is of type Int, then the correct one would look like this:

res.valueForKey("idade") as? Int

But you should take advantage of the object typing that CoreData offers you.

Simply enter the xcdatamodel file, select its entities, and through the top menu Editor - > Create NSManagedObject subclass

So your code would be a lot simpler:

var results =  try context.executeFetchRequest(request) as! [Pessoa]

if(results.count > 0){
   var res = results[0]

   nomeText.text = res.nome
   idadeText.text = res.idade.description
}

Source: link

    
23.10.2015 / 14:58
0

Numeric values in CoreData are mapped to NSNumber .

To assign as a text to UITextField you must explicitly request the value as string:

let idade : NSNumber = res.valueForKey("idade")
idadeText.text =  idade.stringValue()
    
23.10.2015 / 14:22