IOS Key-Value Observing (KVO), key-valuekvo

Source: Internet
Author: User

IOS Key-Value Observing (KVO), key-valuekvo

Kvo, similar to the observer mode, detects object changes by setting an observer for the specified object. After the attribute of the specified object is modified, the object used as the observer will receive the notification. In short, kvo automatically notifies the corresponding observer after the attribute of the specified object to be observed is modified. The system framework already supports kvo, so it is very convenient to use it directly during development.

I. Procedure for using kvo

1. Register, specifying the attributes of the observer

2. Implement callback Methods

3. Remove observation

Ii. Introduce the usage of kvo through small examples in reality

I have a bank card. As long as the amount in the card changes, the bank will send a text message to me. The following code uses kvo to simulate this process.

First, create a Card bank Card class with the property of money amount in the Card. When initializing this Card, set an initial value of 1000 for the Card amount, and then simulate the consumption of 10 yuan every second, the Code is as follows:

  Card. h

// Card. h // KVO // Created by jerei on 15-6-5. // Copyright (c) 2015 jerehedu. all rights reserved. // # import <Foundation/Foundation. h> @ interface Card: NSObject @ property (nonatomic, assign) float money; @ end

Card. m

// Card. m // KVO // Created by jerei on 15-6-5. // Copyright (c) 2015 jerehedu. all rights reserved. // # import "Card. h "@ implementation Card-(instancetype) init {if (self = [super init]) {_ money = 1000.0; [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: @ selector (changeMoney) userInfo: nil repeats: YES];} return self;} // change the amount in the card-(void) changeMoney {self. money-= 10;} @ end

Create another People human, which has two attributes: name and card.

People. h

// People. h // KVO // Created by jerei on 15-6-5. // Copyright (c) 2015 jerehedu. all rights reserved. // # import <Foundation/Foundation. h> @ class Card; @ interface People: NSObject @ property (nonatomic, copy) NSString * name; @ property (nonatomic, strong) Card * card;-(id) initWithName :( NSString *) name andCard :( Card *) card; @ end

People. m

// People. m // KVO // Created by jerei on 15-6-5. // Copyright (c) 2015 jerehedu. all rights reserved. // # import "People. h "# import" Card. h "@ implementation People-(id) initWithName :( NSString *) name andCard :( Card *) card {if (self = [super init]) {_ name = name; _ card = card;} return self;} @ end

After two classes are created, kvo is used in the People class to monitor the amount changes in the bank card.

1. You need to monitor the amount in your bank account and register the listener object.
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

The called method is the Monitored object with the following parameters:

AddObserver: Observer

ForKeyPath: The property of the Monitored object. The property also contains the property. You can use the dot syntax.

Options: the operation of the object to be monitored, such as initialization and new value.

Context: context, which is generally nil. When KeyPath: is the same, it can be used to distinguish

Therefore, the code to be added in People. m is:

-(Id) initWithName :( NSString *) name andCard :( Card *) card {if (self = [super init]) {_ name = name; _ card = card; // register and add the observer [_ card addObserver: self forKeyPath: @ "money" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];} return self ;}
2. Once registered, You can perceive the change process in the callback function.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;

ObserveValueForKeyPath: String, monitored attribute

OfObject: Which object is listened on

Change: a dictionary that contains the values before and after the change.

Context: context

Therefore, the callback method must be implemented in People. m.

-(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context {NSLog (@ "Callback method % @", change );}
3. Release the listener object
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;

The method is the Monitored object.

RemoveObserver: Observer

ForKeyPath: String

Therefore, the dealloc method is rewritten in People. m to remove listeners.

-(void)dealloc{    [_card removeObserver:self forKeyPath:@"money"];}
4. ps: The kvo attribute value cannot be changed directly.

In this example, the Card class has a changeMoney method, which modifies the value of the listener attribute. The following describes the methods in section 4.

-(Void) changeMoney {// you cannot directly change the value !!!! _ Money-= 10; // incorrect // 1. point syntax self. money-= 10; // 2. set Method float f = _ money-10; [self setMoney: f]; // 3. kvc [self setValue: @ (f) forKey: @ "money"]; // 4. [self willChangeValueForKey: @ "money"]; _ money-= 10; [self didChangeValueForKey: @ "money"];}


If you have any questions or technical exchanges, please join the official QQ group: (452379712)

Author: Jerry Education
The copyright of this article belongs to Yantai Jerry Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the author's consent and provide the original article connection on the article page, otherwise, you are entitled to pursue legal liability.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.