The realization principle and application of IOS--KVO

Source: Internet
Author: User
Tags uikit

This paper is divided into 2 parts: concept and application .

The concept section aims to analyze the implementation principle of the design pattern of KVO, and to illustrate the role of KVO technology in the development of iOS by using the project created.

If it is just contact KVO beginners, you can understand the basic principles after a cursory look at the bottom of the implementation of the principle, and then read the second part of the application of "learning" how to use Kvo, and then slowly in-depth understanding KVO this one " The principle of "black magic" technology.

" This development environment: xcode:7.2 IOS Simulator:iphone6 by: Ah left this article D emo Download Link: Kvo Demo demo "

---------------------------------------------------------Concept---------------------------------------------------------

What is KVO?  

    • KVO is an implementation of the Objective-c design pattern for the Observer . "The other is: notification mechanism (notification), detailed reference: IOS amusing design mode-notification ";
    • KVO provides a mechanism for specifying an object to be observed (for example, a), and when a property of an object (such as the string name in a) changes, the object is notified and processed accordingly; "and you don't need to add any extra code to the object being observed, you can use the KVO mechanism"

Under the MVC Design Architecture project, the KVO mechanism is well suited for communicating between the mode model and view views.

For example: In the code, create the attribute data in model Class A, create the observer in the Controller, and once the attribute data changes, receive the notice that the observer receives the notification, and then use the callback method in the controller to process the update of view B by Kvo, (the application in this article is an example of this.)

Second, the realization principle?

The API documentation for KVO in Apple is as follows:

Automatic Key-value Observing is implemented using a technique called isa-swizzling ... When a observer is registered for a attribute of an object the ISA pointer of the observed object is modified, pointing To a intermediate class rather than at the true class ...

the implementation of KVO relies on the objective-c powerful runtime "can refer to: Runtime of a few small examples ," from the above Apple 's documentation can be seen Apple's implementation of the KVO mechanism is a , and the details are not described too much, but we can explore the underlying implementation principle of the KVO mechanism through the method provided by the runtime. To do this , left. Some information about KVO on the Internet summarizes the relevant contents:

the basic principle :

When observing an object A, the KVO mechanism dynamically creates a subclass of object A's current class and overrides the setter method of the observed attribute KeyPath for this new subclass. The setter method is then responsible for notifying the changing state of the observed object's properties.

In- depth analysis :

Apple uses Isa mixed write (isa-swizzling) to implement KVO. when observing object A, the KVO mechanism dynamically creates a new class named: Nskvonotifying_a, which inherits from the class of object A, and KVO for Nskvonotifying_a overrides the observation property. Setter method , the setter method is responsible for notifying all observed object property values of changes before and after invoking the original setter method.

( Note: Isa mixed-write (isa-swizzling)isa:is a kind of; Swizzling: mixed, stirred;)

①nskvonotifying_a: In this process, the ISA pointer of the observed object points from the original Class A and is modified by the KVO mechanism to point to the newly created subclass of the system. Nskvonotifying_a class, to realize the current class property value change monitoring ;

So when we look at the application level, completely unaware of the emergence of new classes, this is the system "hide" the kvo of the bottom of the implementation process, let us mistakenly think or the original class. But at this point if we create a new class called "nskvonotifying_a" (), we find that the program crashes when the system runs to the code that registers the KVO, because the system dynamically registers for monitoring An intermediate class named Nskvonotifying_a was created and pointed to the middle class.

(the role of theIsa pointer: Each object has an Isa pointer to the object's class, which tells the Runtime what the class of the object is.) So when an object is registered as an observer, theISA pointer points to the new subclass, and the observed object magically becomes the object (or instance) of the new subclass. Therefore, the call to the setter on the object invokes the overridden setter, which activates the key-value notification mechanism.

I guess, this is also the KVO callback mechanism, why are commonly known as KVO technology as one of the reasons for Black Magic Bar: Internal mystery, appearance concise.

② subclass Setter method anatomy: Kvo : willchangevalueforkey: and  didchangevlueforkey:, < span class= "s2" >

Before the observed attribute changes , Willchangevalueforkey: Called, notifies the system that the property value of the keypath is about to change; When the change occurs , Didchangevalueforkey: Called to notify the system that the KeyPath property value has changed , and then ObserveValueForKey:ofObject:change:context: is also called. And the setter method that overrides the observation property is implemented at runtime rather than at compile time.

The KVO for the Observer property of the subclass override call accessor method works in code equivalent to:

-(void) SetName: (NSString *) newname{    [self willchangevalueforkey:@ "name"];    KVO always calls    [super Setvalue:newname forkey:@ "name"] before invoking the access method, and//invokes the access method of the parent class    [self didchangevalueforkey:@ "name"] ;     KVO the total call after calling the access method}

Third, Characteristics:

The Observer observes the attribute and executes the KVO callback method only if the KVO changes the property value , such as whether the setter method is executed, or whether the KVC assignment is used . If the assignment does not pass the setter method or KVC, the member variable corresponding to the property is modified directly, for example: only _name = @ "newName"is called, and this is not triggered KVO mechanism, the callback method is not called more .

So the premise of using the KVO mechanism is to change the property value by following the KVO property setting.

Iv. steps

    1. Register observer, implement monitoring;
    2. Handle the change of the property in the callback method;
    3. Removing observers

---------------------------------------------------------Application---------------------------------------------------------

Five. Implementation methods (methods in the Apple API documentation):

A. Registered Observer:
The first parameter observer: The Observer (observe the property change of the Self.mykvo object here)//The second parameter keypath: the observed property name (see the change of num attribute value in SELF.MYKVO here)//The third parameter options: Observe some of the configuration of the new value of the property, the old value, etc. (enumeration value, can be set as needed, for example, two items can be used here)//Fourth parameter context: Context, you can pass a value for Kvo callback method (for example, set as a dictionary to put data)//register Observer [SELF.MYKVO addobserver:self forkeypath:@ "num" options:nskeyvalueobservingoptionold| Nskeyvalueobservingoptionnew Context:nil];

B. when the value of the property (KeyPath) is sent a change, a notification is received that calls the following method:

KeyPath: Property name//object: Observed object//change: Values before and after changes are stored in the change dictionary//context: When registering the Observer, the context passes over the value-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<nsstring *,id> *) Change Context: (void *) context{}

Six, the code ~:

1. Create a new project, the UI interface is designed as follows: The first is a sticky note for displaying num values, associating Viewcontroller and naming: label;

The second is the button, which is used to change the value of NUM, associating Viewcontroller and named: Changenum.

2. Model Creation "Create a new file, select Cocoa Touch Class, named" Mykvo ", and remember to select subclass of" NSObject ". The code is as follows:

(myKVO.h):

@interface Mykvo:nsobject@property (nonatomic,assign) int num; The Num@end property is set to type int

(MYKVO.M):

#import "myKVO.h" @implementation mykvo@synthesize num; @end

3. Listen and respond to property changes in Viewcontroller.

(ViewController.h):

#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller@property (weak, nonatomic) Iboutlet UILabel * label;//Note label-(ibaction) Changenum: (UIButton *) sender;           Button Event @end

(VIEWCONTROLLER.M):

#import "ViewController.h" #import "MyKVO.h" @interface Viewcontroller () @property (nonatomic,strong) Mykvo *mykvo;@        End@implementation viewcontroller-(void) viewdidload {[Super viewdidload];        SELF.MYKVO = [[Mykvo alloc]init];      /*1. Registered object MYKVO as the Observer: option, Nskeyvalueobservingoptionold provides "initial object data" in the form of a dictionary;     Nskeyvalueobservingoptionnew "Updated new data" in the form of a dictionary; */[SELF.MYKVO addobserver:self forkeypath:@ "num" options:nskeyvalueobservingoptionold| Nskeyvalueobservingoptionnew Context:nil];} /* 2. This callback method is called as long as the KeyPath property of object changes, and is processed accordingly: UI update: */-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: ( ID) object change: (nsdictionary<nsstring *,id> *) Change context: (void *) context{if ([KeyPath isequaltostring:@ " Num "] && object = = Self.mykvo) {//Response change Processing: UI Update (label text change) Self.label.text = [NSString stringwith                format:@ "The current num value is:%@", [Change valueforkey:@ "new"]; Use of change: The enumeration is 2 at the time of registration, so you can extract both methods of the new and old values in the change dictionary NsloG (@ "\noldnum:%@ newnum:%@", [Change valueforkey:@ "old"],[change valueforkey:@ "new"]);        }}-(void) didreceivememorywarning {[Super didreceivememorywarning]; /* 3. Remove KVO */[Self removeobserver:self forkeypath:@ "num" Context:nil];} Button Event-(ibaction) Changenum: (UIButton *) Sender {//press once to make Num's value +1 self.myKVO.num = Self.myKVO.num + 1;} @end

Debug: Note Label initialization has no numeric value, and when the label record num increments after each click of the button, the KVO mechanism sends a notification when the button causes the property num to increase, and calls the Observevalueforkeypath: method to make the UI update. ( This article Demo download Link:kvo demodemo)

Vii. Expansion and

1. Different from the KVC?

    • KVC (Key-value encoding), Key-value Coding, an informal protocol, uses a string (key) to access the mechanism of an object instance variable. Rather than by invoking the setter, getter method, and other explicit access methods.
    • KVO (Key-value listener), Key-value observing, provides a mechanism for objects to be notified when the properties of a specified object are modified, provided that the setter method is executed, or the KVC assignment is used.

2. What is the difference between notification (notice)?

    • Notification more than KVO a step to send notifications.
    • Both are one-to-many, but the direct interaction between the objects is significantly notification and requires notificationcenter to be an intermediate interaction. And KVO as we introduced, set the observer---processing property changes, as for the middle notice this ring, then more secret, only leave a sentence "by the system notice", the concrete can refer to the above realization process analysis.

The advantage of notification is that the monitoring is not limited to the change of the property, but also can listen to a variety of state changes, wide range of monitoring, such as the keyboard, the front backstage and other system notification use is also more flexible and convenient. (Refer to the notification mechanism in section fifth, system notification name content:)

3. Different from the delegate?

Like delegate, KVO and Nsnotification are the communication between classes and classes. But unlike the delegate, it is:

    • Both are responsible for sending and receiving notifications, the rest is handled by the system, so there is no return value, whereas the delegate needs to communicate with the object through the variable (proxy) contact;
    • Delegate is just one-to-one, and these two can be a couple.

4. Technology involved:

The fundamental of KVC/KVO implementation is the dynamic and runtime of objective-c, and the realization of accessor method;

Summarize:

Compared with other callback methods, theimplementation of the KVO mechanism is more supported by the system, more concise than notification, delegate and so on, and can provide the newest value of the observation attribute and the original value, but corresponding in creating the subclass, The memory consumption in terms of overriding methods and so on is huge. So for the communication between the two classes, we can use different methods according to the actual development environment, which makes the project of development more concise and practical.

It is also important to note that because the injection of this inheritance is implemented at runtime and not at compile time, KVO does not have any overhead if the given instance has no observers, because there is no KVO code at this time. But even without observers, delegates and Nsnotification still have to work, which is also the advantage of KVO here with 0 overhead observations.

The realization principle and application of IOS--KVO

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.