return Coredat - Swift

Asked

Viewed 52 times

2

I am unable to assign a textField with the result of a search when it is int, with the right string

 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 the print it returns me nil.. when it changes to Int, it returns me correct value.. how do I assign the textField with this value, remembering that with the field name I do not have this error

2 answers

3


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

res.valueForKey("idade") as? Int

But, you should take advantage of the type of objects that Coredata offers you.

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

So your code would be much 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: https://developer.apple.com/library/ios/recipes/xcode_help-core_data_modeling_tool/Articles/creating_mo_class.html

  • Thanks for the help Fernando, I knew it would have to be the as? Int, I just wasn’t able to put in textField. I followed your advice and it worked I just had to put ! in idadeText.text = res.idade!. Description

  • the "!" sign is required if your attribute is marked as Optional (a "?" next to the type), in which case you can keep the nil value. Through the graphical interface of the xcdatamodel file, you can customize this.

  • I read more about it here http://themsaid.github.io/2015/04/16/core-data-from-scratch-with-swift/ Thank you again

2

Coredata numerical values are mapped to NSNumber.

To assign as text to UITextField you must explicitly ask for the value as string:

let idade : NSNumber = res.valueForKey("idade")
idadeText.text =  idade.stringValue()
  • Thanks, it was a little different, I believe because of the version of Swift Let age: Nsnumber = res.valueForKey("age") as! Int idadeText.text = age.stringValue

  • Feel free to edit the question . I am Objc programmer I’m still not used to the syntax of swift. Admittedly, if the answer has been useful to you, please accept it as correct.

  • 1

    Oops, sorry.. I’m new here and I couldn’t find my mark.. and my vote for now doesn’t compute :/ , but thanks again

Browser other questions tagged

You are not signed in. Login or sign up in order to post.