English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Summary and Differences of KVC, KVO, Notification, and Delegate in iOS
1KVC, which stands for NSKeyValueCoding, is an informal Protocol that provides a mechanism for indirectly accessing an object's properties, rather than accessing them through Setter and Getter methods. KVO is one of the key technologies implemented based on KVC.
Demo:
@interface myPerson : NSObject { NSString*_name; int _age; int _height; int _weight; } @end @interface testViewController :UIViewController @property (nonatomic, retain) myPerson*testPerson; @end - (void)testKVC { testPerson = [[myPerson alloc] init]; NSLog(@"testPerson’s init height =%@", [testPerson valueForKey:@"height"]); [testPerson setValue:[NSNumber numberWithInt:168] forKey:@"height"]; NSLog(@"testPerson’s height = %@", [testPerson valueForKey:@"height"]); }
The first piece of code defines a class myPerson, which has a _height property but does not provide any getter/setter access methods. At the same time, in the testViewController class, there is a pointer to the myPerson object.
Generally speaking, after the myPerson instance is instantiated, it is impossible to access the _height property of this object. However, through KVC, we have achieved this, and the code is the testKVC function.
After running, the printed value is:
2015-3-13 11:16:21.970 test[408:c07] testPerson’s init height = 0
2015-3-13 11:16:21.971 test[408:c07] testPerson’s height = 168
This indicates that the _height property has indeed been read and written.
Common methods of KVC:
- (id)valueForKey:(NSString *)key; -(void)setValue:(id)value forKey:(NSString *)key;
The valueForKey method reads the property of an object based on the value of the key, and setValue:forKey: writes the property of an object based on the value of the key.
Note:
).1The value of the key must be correct; if there is a spelling error, an exception will occur.
).2When the value of the key is undefined, the method valueForUndefinedKey will be called. If you have written this method, the value of the key will trigger this method when there is an error.
).3Due to the repeated nesting of class keys, there is a concept of keyPath. The keyPath is used to link keys one by one with the dot symbol, so that properties can be accessed according to this path.
).4). NSArray/NSSet all support KVC
2KVO stands for KeyValue Observe, which is the abbreviation in Chinese for key-value observation. This is a typical observer pattern, where the observer receives notifications when the key-value changes. iOS has a Notification mechanism that can also obtain notifications, but this mechanism requires a Center. Compared to KVO, it is more concise and direct.
The usage of KVO is also very simple, it is just simple3Step.
1.注册需要观察的对象的属性addObserver:forKeyPath:options:context:
2.Implement the observeValueForKeyPath:ofObject:change:context: method, which is automatically called when the observed property changes
3.取消注册观察removeObserver:forKeyPath:context:
Demo:
@interface myPerson : NSObject { NSString *_name; int _age; int _height; int _weight; } @end @interface testViewController : UIViewController @property (nonatomic, retain) myPerson *testPerson; - (IBAction)onBtnTest:(id)sender; @end - (void)testKVO { testPerson = [[myPerson alloc] init]; [testPerson addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew context:nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"height"]) { NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]); } else {}} [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } - (IBAction)onBtnTest:(id)sender { int h = [[testPerson valueForKey:@"height"] intValue]; [testPerson setValue:[NSNumber numberWithInt:h+1]; NSLog(@"person height=%@", [testPerson valueForKey:@"height"]); } - (void)dealloc { [testPerson removeObserver:self forKeyPath:@"height" context:nil]; [super dealloc]; }
The first piece of code declares the myPerson class, which has a _height property. In testViewController, there is a pointer to the testPerson object.
In the testKVO method, we registered the observation of the height property of the testPerson object, so that we will receive a notification when the height property of testPerson changes. In this method, we also pass the new value in the dictionary by requiring the NSKeyValueObservingOptionNew parameter.
The observeValueForKeyPath:ofObject:change:context: method is overridden, and the change in this method contains the corresponding value in the NSDictionary object.
It should be emphasized that the callback of KVO must be called, and the properties must be modified through the methods of KVC. If the properties are modified by calling other methods of the class, the observer will not receive any notifications.
3.The usage of NSNotification can be seen at http://blog.csdn.net/eduora_meimei/article/details/44198909
Differences:
Advantages of delegate:
1.Very strict syntax. All events to be heard must be clearly defined in the delegate protocol.
2.If a method in the delegate is not implemented, a compilation warning will appear./Error
3The protocol must be defined within the scope of the controller
4The control flow in an application is traceable and identifiable;
5Multiple different protocols can be defined in a controller, each with different delegates
6No third-party object is required to maintain/Monitor the communication process.
7It can receive the return value of the called protocol method. This means that the delegate can provide feedback information to the controller
Disadvantages :
1A lot of code needs to be defined:1Protocol definition2The delegate property of the controller3Delegate methods are implemented within the delegate itself
2When releasing the proxy object, you need to carefully set the delegate to nil. If the setting fails, calling the method to release the object will cause a memory crash
3In a controller, there may be multiple delegate objects, and delegates adhere to the same protocol, but it is still difficult to tell the same event to multiple objects, although it is possible.
Advantages of notification :
1No need to write much code, implementation is relatively simple;
2For a notification issued, multiple objects can respond, i.e.,1Implementation is simple in multiple ways
3The controller can pass a context object (dictionary), which carries custom information about the notification sent
Disadvantages :
1There is no check at compile time to see if the notification can be correctly handled by the observer;
2When unregistering the registered objects, you need to unregister from the notification center;
3The working and control process in debugging is difficult to track;
4Third-party management is required to manage the relationship between the controller and observer objects;
5The controller and observer need to know the notification name, UserInfodictionary keys in advance. If these are not defined in the workspace, there will be unsynchronized situations;
6After the notification is issued, the controller cannot obtain any feedback information from the observer.
Advantages of KVO :
1It can provide a simple method to achieve synchronization between two objects. For example: synchronization between model and view;
2It can respond to the state changes of non-self-created objects, i.e., the internal object (SKD object), without changing the implementation of the internal object;
3It can provide the latest and previous values of the observed properties;
4Observing properties using key paths, so nested objects can also be observed;
5The abstraction of the observed object is completed, as no additional code is needed to allow the observed value to be observed
Disadvantages :
1The properties we observe must be defined using strings. Therefore, there will be no warnings or checks at the compiler level;
2Refactoring properties will cause our observation code to no longer be available;
3Complex 'IF' statements require the object to be observing multiple values. This is because all the observation code points to a method through one method;
4When releasing the observer, there is no need to remove the observer.
1Efficiency is definitely higher than NSNotification.
Delegate methods are more direct than notifications, the most typical feature of which is that delegate methods often need to pay attention to the return value, that is, the result of the delegate method. For example-windowShouldClose:, needs to care about whether the return is yes or no. Therefore, delegate methods often contain the very expressive word 'should'. That is, if you are my delegate, I will ask you if you are willing to close the window for me? You need to give me an answer, and I will decide how to proceed next based on your answer. On the contrary, the biggest feature of notification is that it does not care about the attitude of the recipient, I just put out the announcement, whether you accept it or not is your business, and I also do not care about the result. Therefore, notification often uses the word 'did', such as NSWindowDidResizeNotification, then after the NSWindow object emits this notification, it will not take care of anything and will not wait for the recipient's reaction.
2The differences between KVO and NSNotification:
Like delegate, the role of KVO and NSNotification is also communication between classes, which is different from delegate1Both of these are responsible for sending notifications, and the rest is not taken care of, so there is no return value;2The delegate is one-to-one, while these two can be one-to-many. They also have their own characteristics.
Thank you for reading, I hope it can help everyone, thank you for your support to our website!