0

I'd like to tie a core-data entity to a UITextField so that whenever the the textField finishes editing, it will automatically update the core-data object.

Here's how I'd like it work– not sure if it's possible.

  • user is a core-data entity
  • user.gender is a field of that entity
  • genderField is a UITextField
  • genderField.coreDataObject is a NSManagedObject property

    1. A user types content into a genderField
    2. On finish, the genderField fires didEndEditing
    3. In didEndEditing, the genderField sets the user.gender by saying genderField.coreDataObject = genderField.text

The problem is that the coreDataObject is the user and not user.gender. So, first of all, you can't set the coreDataObject equal to a string.

I need to store coreDataObject but then somehow set coreDataObject.gender = genderField.text

Thanks.

Brian Weinreich
  • 7,692
  • 8
  • 35
  • 59
  • What's the error/is happening? Does it crash? – Rich Apr 17 '14 at 19:10
  • Just updated my question because I wasn't clear. The problem is that the coreDataObject is the user and not user.gender. So, you can't set the coreDataObject equal to a string. I need to set `coreDataObject.gender = genderField.text` but am not sure how to access that property – Brian Weinreich Apr 17 '14 at 19:15
  • Have you generated classes for your `NSManagedObject` entity? If not try `[genderField.coreDataObject setValue:genderField.text forKey:@"gender"]`. – Rich Apr 17 '14 at 19:18
  • Whoa- Awesome! That works! Okay I didn't realize you could set it like that. If you want to put that as an answer below, I will mark it as the correct answer – Brian Weinreich Apr 17 '14 at 19:26
  • As an addendum, have you considered generating NSManagedObject subclasses for your entities? It would make it possible to access their properties via standard getters/setters, and give you all those sweet, sweet, compile time checks. – AlexDG Apr 17 '14 at 19:29
  • @BrianW thanks, and glad it worked. I've referenced another answer in mine if you want to go down the custom `NSManagedObject` route :) – Rich Apr 17 '14 at 19:32
  • You are mixing model and view, don't you? You should set your view controller as delegate for the text field and receive a notice when ever the text changes and save its new value in CD. – Hermann Klecker Apr 17 '14 at 19:37

1 Answers1

0

You can either generate custom subclass your NSManagedObject or use key-value coding.

[genderField.coreDataObject setValue:genderField.text forKey:@"gender"]

As echoed by AlexDG, you might be better off eventually going down the generating route. But for now the above works for your needs!

See this answer for more info on generating your own classes!

Community
  • 1
  • 1
Rich
  • 8,108
  • 5
  • 46
  • 59