preface

Learning is like rowing upstream, not to advance is to drop back! Mutual encouragement!!

12, You cease to live, you cease to learn. Today is November 1st, taobao pre-sale has already begun. I don’t know if your nuggets brothers and sisters are starting to chop. Today to dig gold, mainly to share with you a iOS seven or eight years of the elderly on KVO experience summary. Without further ado, I will share it with you now. You can support it with likes and attention. Ps: Because I translated English, if there is any mistake is not accurate, please also criticize the comment area.

kvo

1. Kvo is introduced

KVO is a mechanism that allows an object to be notified when a specified property of another object changes.

Important: In order to understand KVO, you must first understand the decoding of KVO

2. General process of KVO

// Key-value observation provides a mechanism for notifying other objects of changes to specific properties. Is particularly useful for model and controller layer communication between applications. (In OS X, controller layer binding technology relies heavily on key-value observation.) Controller objects typically observe the properties of the model object, and a view object observes the properties of the controller model object. In addition, however, a model object can be observed by other model objects (usually to determine when the relevant value changes), or even itself (again to determine when the value of a dependency changes).

// You can observe properties including simple properties, one relationship, and many relationships. Many observers of the relationship are informed of the type of change and which objects are involved in the change.

// A simple example illustrates how KVO can be useful in applications. Suppose a Person object and an account object represent the Person’s bank savings account. Instance people may need to know when some aspect of the account instance changes, such as balance, or interest rates.

// If these attributes were of a public account nature, one could poll the account periodically to find changes, but this is of course inefficient and often impractical. A better approach is to use KVO, which is similar to what happens when a person receives an interrupt.

// To use KVO, first you must ensure that the observation object, account in this case, is KVO compatible. In general, if your object inherits NSObject and creates properties in the usual way, your object and its properties will automatically be KVO compatible. Compliance can also be implemented manually. KVO compliance describes the difference between automatic and manual key-value observation and how to achieve it.

// Next, you must register your observers, people, observed instances, accounts. Person sends an addObserver:forKeyPath: Select: background :Account information, once for each observation critical path, naming itself as the observer

/ / in order to receive notification of changes in the Account, people realized the observeValueForKeyPath: ofObject: change: background: method, requiring that all observers. The account will send this message to the person any time a critical path change is registered. A person may take appropriate action based on change notification

/ / in the end, when it no longer wants to notice, at least, before the Person instance must cancel sending messages removeObserver: forKeyPath: Account.

Registration key observation describes the full life cycle of registration, key observation receiving, deregistration notification.

// The main benefit of KVO is that you don’t have to implement your own plan to send notifications every time a property changes. Its well defined infrastructure-frameworklevel support, easy to adopt- task you don’t need any code to add to your project. In addition, the infrastructure is already fully functional, which makes it easy to support multiple observers for a property, as well as related values.

The registration related key explains how to specify one key value dependent on another key value

// Unlike notification using NSNotificationCenter, there is no central object that provides change notification for all observers. Instead, direct notifications are sent to the observed object for changes made. NSObject provides observations of key values for this basic implementation, and you should rarely need to override these methods.

// Key-value observation implementation details describe how to implement key-value observation.

3. Registration of KVO

// You must perform the following steps to enable the object to receive a key observation notification for kVO-Compliant:

  • Use method to register observer and view object addObserver:forKeyPath:.
  • / / implementation observeValueForKeyPath: ofObject: change: context: accept change notification message in the observer
  • / / cancellation of observer method using removeObserver: forKeyPath: when it should no longer receive messages. At the very least, the observer is freed from memory before the method is called.

// Important: Not all classes are KVO-compliant with all attributes. You can ensure that your classes are KVO-compliant and follow the steps described in KVO compliance. Usually the apple-supplied attribute frameworks are only Kvo-compliant if they are recorded.

4. Registered observer of KVO

// An observed object first sends the register itself with the observed object an addObserver:forKeyPath: select: background: message, passing its own observer and critical path properties to be observed. The observer additionally specifies an option parameter and a context pointer to manage notifications.

Options(enumeration of KVO)

The option argument, specified as a constant bitwise or option, will both affect how the dictionary contents are changed to provide notifications and how the notifications are generated. The observed before you choose to accept the value of the attribute change NSKeyValueObservingOptionOld by specifying the options. You request with the new value of the option NSKeyValueObservingOptionNew attribute. You receive new and old values by bit or these options.

/ / direct observation object you send change notification immediately (before the addObserver: forKeyPath: choice: background: return) NSKeyValueObservingOptionInitial option. You can use these additional, one-time notifications to set up the initial value of the property in the observer.

/ / direct observation object to send you a notice before the property change (in addition to the usual notification, the change), including choosing NSKeyValueObservingOptionPrior. Dictionary represents the changes include key NSKeyValueChangeNotificationIsPriorKey prechange inform NSNumber packaging value for sure. The point is that it doesn’t exist. When you can use Prechange to notify an observer of the KVO compliance need to invoke a so… One of its properties, the method depends on an observed property. The usual call to the bookkeeping will notify too late… .

Context (KVO Context)

// Context pointer addObserver:forKeyPath: select: background: message containing arbitrary data will be passed back to the observer on corresponding change notification. You can specify NULL and completely depend on the critical path string to determine the origin of the change notification, but this approach can cause problems for an object of the superclass that also observes the same critical path for different reasons.

// A safer and more extensible approach is to use context to ensure that you receive notifications from your observer, rather than a superclass.

// Address uniquely named static variables in your class context. Context selection in a similar manner in super – or subclasses may overlap. You can select a notification message for the entire class and context-dependent critical path string to confirm the change. Alternatively, you might create a different context for each observation critical path, bypassing the need for string comparison completely, leading to more efficient notification resolution. Listing 1 shows the way in which the sample environment balance and loan rate properties are selected.

  • Listing 1 creates a context pointer:

// The example in Listing 2 demonstrates how a person instance register itself can use a given context pointer for an account instance as an observer for the asset and loan rate properties.

// Listing 2 Registered examiner as observer of balance and interest rate attributes

// Note: key value view addObserver:forKeyPath: select: background: method does not hold strong view object reference, view object, or context. You should make sure that you maintain strong references to observations, observations, objects and context when necessary

Receiving Notification of a Change

/ / they observed the change of the value attribute of the object, the observer receives a observeValueForKeyPath: ofObject: change: background: message. All observers must implement this method.

// The observed object provides the critical path, which raises the notification, is itself the relevant object, a dictionary, which contains the details of the changes, and the context pointer, which is provided when the observer registers the critical path.

// Change the type of information provided by the dictionary entry NSKeyValueChangeKindKey changes. If the value object observed changes, the NSKeyValueChangeSetting NSKeyValueChangeKindKey entry returns. The options specified depend on whether the NSKeyValueChangeOldKey and NSKeyValueChangeNewKey entries in the dictionary contain the value of the attribute before, and after changing at observer registration time. If the property is an object, provide the value directly. If the property is a scalar or C structure, wrap it in a value NSValue object (with key-value encoding).

/ / if the property is a lot of observed, the relationship between NSKeyValueChangeKindKey entries also indicates the relationship object is inserted, deleted, replaced, or return to NSKeyValueChangeInsertion NSKeyValueChangeRemoval, or NSK EyValueChangeReplacement, respectively.

/ / change NSKeyValueChangeIndexesKey dictionary entry is a NSIndexSet object specified index relationship has changed. If NSKeyValueObservingOptionNew or NSKeyValueObservingOptionOld as options specified registered observers, change the dictionary NSKeyValueChangeOldKey and NSKeyValueChangeNew The Key entry array contains the values of the related objects before, after, and after changes. The example in listing 3 shows the observeValueForKeyPath: ofObject: change: background: to achieve the balance of old and new value attribute in log of observer and loan interest rates, as listing 2 registration.

Listing 3 Implementation of observeValueForKeyPath:ofObject:change:context:

// If you specify an empty context when registering an observer, you compare the notification critical path with the critical path you observe to determine what has changed. If you use a context to observe all the critical paths you first test, notify the context, and find a match, use the critical path string comparison to determine exactly what has changed. If you provide a unique context for each critical path, as demonstrated in this article, a series of simple pointer comparisons simultaneously tell you whether to inform the observer, and if so, what the critical path changes.

// In any case, the observer observeValueForKeyPath should call the superclass’s implementation :ofObject: change: background: when it does not recognize the context (or in the simple case, any critical path), because that means a superclass registers notifications. Note: if a notice at the top of the class hierarchy, NSObject thrown NSInternalInconsistencyException because this is a programming error: use it without a subclass registration notice.

6.Removing an Object as an Observer

/ / you delete a key-value watchers by sending objects removeObserver: forKeyPath: background: information, specify the observation object, the critical path and context. The example in Listing 4 shows the person removing itself as an observer of the balance and loan rate.

Listing 4 removes the checker as an observer of balance and interestRate

/ / after receiving removeObserver: forKeyPath: background: news, people will no longer receive any observeValueForKeyPath: ofObject: change: background: messages to specify the critical path and objects.

When removing an observer, keep several points in mind

  • // Request removal as an observer if not NSRangeException has been registered as a result. You can either call removeObserver: forKeyPath: background: exactly a corresponding call addObserver: forKeyPath: choice: background:, or if in your application, this is not feasible to place removeObserver: forKeyPath: background: Handle potential exceptions in a try/catch block.

  • // An observer itself does not automatically delete when retracted. The observer continues to send notifications, ignoring the state observer. However, change notifications, like any other information, are sent to the publishing object, triggering a memory access exception. So make sure the observer is removed from memory before he disappears.

  • // The protocol provides no way to ask whether an object is an observer or being observed. Build your code to avoid releasing associated errors. The typical pattern is to register an observer at the initialization of the observer (such as in init or viewDidLoad) and unregister at the dealloc dealloc(usually), ensure the correct pairing and command to add and remove messages that the observer is unregistered before being released from memory.

7:KVO Compliance (KVO To Note)

In order to be considered KVO compatible for a specific property, a class must ensure the following:

  1. // The class must encode the key value of the property specified in ensuring existing compliance.

  2. //KVO supports the same data types as existing ones, including scalars and structure and structure support listed in Objective-C objects and scalars.

  3. // Class emission KVO property change notification.

4.// Rely on keys to register appropriate (see registering related keys).

// There are two techniques to ensure that change notifications are issued. NSObject automatically defaults and the support provided is available for all attribute key value encoding compatibility for classes. In general, if you follow standard cocoa coding and naming conventions, you can use automatic change users without writing additional code.

// Manual change notification Notifications provide additional control when issued and require additional encoding. You can control the property class methods that automatically notify your subclasses of their implementation

automaticallyNotifiesObserversForKey:

8:Automatic Change Notification

//NSObject provides a basic implementation of automatic key-value notifications. Automatic key-value change notification notifies the observer of changes in the read/write method using the key value, as well as the key-value encoding method. Also supports automatic notification agent returns a collection of objects, for example, mutableArrayValueForKey:.

// The example shown in Listing 1 results in notification of any observer property name change.

Listing 1 Examples of method calls that cause KVO change notifications to be emitted

9:Manual Change Notification

// In some cases, you may want to control the notification process, for example, to reduce the number of unnecessary application-specific causes that cause notifications or groups to change into a notification. Manual change notifications provide the means.

Manual and automatic notifications are not mutually exclusive. You are free to issue manuals in addition to automatic notifications that are already in place. In general, you may want to have complete control over notification specific properties. In this case, you cover NSObject automaticallyNotifiesObserversForKey:. Attribute automatically inform you want to exclude, automaticallyNotifiesObserversForKey subclass implementation: there should be no return. A subclass implementation should be for any uncalled superkey. The example in Listing 2 allows manual notification of asset ownership and allows the superclass to decide to notify all other keys.

Listing 2 automcallynotifiesobserversforkey implementation examples:

// Implement manual notification to the observer that you call willChangeValueForKey before changing the value, and didChangeValueForKey after changing the value. The example in

Listing 3 implements manual notification for the balance property.

Listing 3 is an example of an accessor method that implements manual notification

// Sending unnecessary notifications can be minimized by first checking if the value has changed. The example in Listing 4 tests the value of the asset if it changes and only provides notification

Listing 4 tests the change in value before providing notification

If a single action causes multiple keys to change, you must nest change notifications, as shown in Listing 5.

Listing 5 nested change notifications for multiple keys

// In an ordered case of many relationships, you must specify not only the key that changes, but also the type and index of the object. Change is a designated NSKeyValueChangeInsertion NSKeyValueChange types, NSKeyValueChangeRemoval or NSKeyValueChangeReplacement. The index of the affected object is passed as an NSIndexSet object. The code snippet in Listing 6 demonstrates how to remove objects encapsulated in many relational transactions.

Listing 6 Implementation of manual observer notification in a to-many relationship

Business Dependent Keys 10:Registering Dependent Keys

// There are many cases where the value of one attribute depends on another object of one or more attributes. Flag that if the value of an attribute changes, the value of the derived attribute should also change. How you ensure that these dependent properties are published depends on the cardinality of the relationship.

11: One-to-one Relationships

/ / trigger automatically notify you should cover keyPathsForValuesAffectingValueForKey: a relationship or a suitable method, follow the schema definition related registration key.

For example, a person’s full name depends on the first and last name. A method that returns the full name can be written as:

// When an application observes a fullName property, it must notify the firstName and lastName properties of changes because they affect the value of the property.

/ / one solution is to cover keyPathsForValuesAffectingValueForKey: specify the fullName property depends on the person’s first name and last name attributes. Listing 1 shows the dependencies for an example implementation:

Listing 1 Example implementation of keyPathsForValuesAffectingValueForKey:

// Override should normally call super and return any included group of members, because it does so (so as not to interfere with override methods).

/ / you can achieve the same result by implementing a class method, follow the naming convention keyPathsForValuesAffecting key < >, < button > where is the name of the attribute (capitalize the first letter), depending on the values. The code in listing 1 USES this model can be written as a class method named keyPathsForValuesAffectingFullName as shown in listing 2.

Listing 2 Example implementation of the keyPathsForValuesAffecting naming convention

/ / you can’t cover keyPathsForValuesAffectingValueForKey: method when you add a computational attributes to the existing class using a category, because you should not cover method category. In this case, to implement a matching keyPathsForValuesAffecting < button > class method using this mechanism.

/ / note: you can’t set up many dependencies by implementing keyPathsForValuesAffectingValueForKey:. Instead, you must comply with the appropriate collection of many attributes for each object and respond to changes in values by updating your own dependency on the key. The following section shows a strategy to handle this situation.

12: To-many Relationships

/ / keyPathsForValuesAffectingValueForKey: does not support the critical path method, including many relations. For example, suppose you have an employee that uses a number of department object relationships (employee), and employee salary attributes. You might want the department object to have a totalSalary attribute that depends on the salary relationships of all employees. You can’t do so, for example, keyPathsForValuesAffectingTotalSalary and returned by the employees. Pay as a key.

  1. In both cases there are two possible solutions:

// You can use the key value to observe all the children (employees in this case) of the relevant property of the registered parent (in this case, department) as the observer. As an observer you must add and remove relationships that the parent adds and removes in child objects (see Register key-value observations). ObserveValueForKeyPath: ofObject: change: background: methods depend on the value of change and update, such as the following code snippet:

  1. If you use core data, you can register the parent with the application’s notification center as the managed object context for the observer. Parents should their children respond in a similar way to notices of changes published by the key value observation.

13: Key-value Observing Implementation Details(KVO Implementation Details)

// Automatic key observation is implemented using a technique called ISA-Swizzling. The ISA pointer, as the name implies, points to the class maintenance schedule of the object. This schedule basically contains the pointing class implementation methods, as well as other data. When an observer registers an object’s property isa the pointer to the observed object is modified to point to an intermediate class rather than to the real class. Because the value of the ISA pointer does not necessarily reflect the actual class instance. You should not rely on isa Pointers to identify class members. Instead, you should use class methods to determine instances of class objects.

Document Revision History

This table describes the modifications to the key-value Observing Programming Guide.

If you think you have any questions, feel free to comment in the comments section. If you need the original PPT, you can get it below. I will also share with you some iOS materials I have collected in recent years. There is truth in the world, iOS circle has warmth. Finally get a thumbs up and a thumbs up.

PPT source to obtain address, iOS information: download address