Wednesday, January 09, 2013

Observation in iOS


                Key value observing (KVO) is a pattern in which one object can observe the value of another object’s properties to find out about changes. Where the previous two patterns (delegation and notifications) are more suited to a controller communicating with arbitrary objects, KVO is more suited for objects of any type listening for changes of another arbitrary object (not necessarily, and most often not a controller). It is a way in which we can keep our objects in sync with one another; a way in which we can make one object react when another object’s state changes. It is only used for properties and cannot be used to respond to methods or other actions.
Pros
  • Can provide an easy way to sync information between two objects. For example, a model and a view.
  • Allows us to respond to state changes inside objects that we did not create, and don’t have access to alter the implementations of (SKD objects).
  • Can provide us with the new value and previous value of the property we are observing.
  • Can use key paths to observe properties, thus nested objects can be observed.
  • Complete abstraction of the object being observed, as it does not need any extra code to allow it to be observed.
Cons
  • The properties we wish to observe, must be defined using strings. Thus no compile time warnings or checking occurs.
  • Re-factoring of properties can leave our observation code no longer working.
  • Complex “IF” statements required if an object is observing multiple values. This is because all observation code is directed through a single method.
  • Need to remove the observer when it is deallocated.

Source
http://blog.shinetech.com/2011/06/14/delegation-notification-and-observation/

No comments:

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...