Question

I am building an app with a view controller that represents a form for creating and editing a Task object. It has the following behaviour:

  1. On initialization of the controller, a Task object (NSManagedObject subclass) is initialized in the MOC
  2. NSNotificationCenter observers are set up for each input in the view.
  3. When an input's value is changed, the corresponding property of the Task object is updated via the observers' assigned method. (eg. - (void)taskNameChanged;)
  4. When the user taps Save, the Task object is committed to the data store. If the user taps cancel, the Task object is discarded from the MOC.

I have a feeling that there is a better way to do this. What is the most common pattern for this type of transaction?

Was it helpful?

Solution

It's uncommon to use notifications in cases like this. The question you need to ask is: Do you need to update it all the time? Most of the times you won't. I usually just the values when the Save button is tapped.

In case you would have to check the values earlier, you still don't want to use notifications. I usually go for hooking up a IBAction to one of the events in Interface Builder. Another option is using the delegate, in that case your UIViewController instance would implement the UITextFieldDelegate protocol.

OTHER TIPS

Unfortunately, iOS lacks Cocoa Bindings, so you end up having to implement a light version yourself.

I did this for our app, and it ended up working well. I used KVO instead of notifications, for two-way binding. I created a dictionary mapping between the object properties and UI elements, and using KVC set up the binding when the view is loaded. In my implementation, I added an option to hint which value should take precedence (this is less valuable for data<->UI, but I wanted something more generic). Eventually, I added support for block-based data transformation between binded objects, so that UI could present text, while the data backing object could hold different types of data.

Please note that UIKit is not KVO compliant. I created KVO-compliant versions of UITextField and UITextView, by listening to notifications and sending the appropriate KVO messages.

While, I cannot post code of this, I hope this gives you ideas regarding your further adventures.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top