Summary and Difference of KVC KVO NSNotification and delegate in iOS

  • 2021-06-28 14:12:59
  • OfStack

Summary and Difference of KVC, KVO, NSNotification and delegate in iOS

1. KVC refers to NSKeyValueCoding, an informal Protocol, which provides a mechanism for indirectly accessing the properties of an object.Instead of calling the Setter, Getter methods.KVO is one of the key technologies based on KVC implementation.

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 code is a class that defines an myPerson with a _The property of height, but no access method to getter/setter is provided.There is also an myPerson object pointer in the testViewController class.

When myPerson is instantiated, this object is normally inaccessible_height attribute, but we did it through KVC, the code is 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 means you did read and write _height property.

Common methods of KVC:

- (id)valueForKey:(NSString *)key; -(void)setValue:(id)value forKey:(NSString *)key;

The valueForKey method reads the object's properties based on the value of key, setValue:forKey:Writes the object's properties based on the value of key.

Be careful:

(1). The value of key must be correct, if misspelled, an exception will occur

(2) When the value of key is undefined, valueForUndefinedKey: This method will be called, and if you write this method yourself, an error in the value of key will be called here

(3). Because the class key is nested repeatedly, there is a concept of keyPath, keyPath links one key with A. sign so that it can be accessed from this path.

(4). Both NSArray and NSSet support KVC

2. KVO is the abbreviation of KeyValue Observe, while Chinese is the key observation.This is a typical observer pattern where the observer is notified when the key value changes.There is an Notification mechanism in iOS that can also be notified, but it requires an Center, which is simpler and more direct than KVO.

KVO is also simple to use, which is a simple three-step process.

1. Register the attribute addObserver:forKeyPath:options:context of the object you want to observe:
2. Implement the observeValueForKeyPath:ofObject:change:context:method, which is called automatically when an observed property changes
3. Unregister Observer 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] forKey:@"height"]; 
  NSLog(@"person height=%@", [testPerson valueForKey:@"height"]); 
} 
 
- (void)dealloc 
{ 
  [testPerson removeObserver:self forKeyPath:@"height" context:nil]; 
  [super dealloc]; 
} 

The first code declares the myPerson class with a _Properties of height.There is an testPerson object pointer in testViewController.

In the testKVO method, we register an observation of the height attribute of testPerson, so that when the height attribute of testPerson changes, it will be notified.In this method, the NSKeyValueObservingOptionNew parameter also requires that new values be passed in to dictionary.

Overrides the observeValueForKeyPath:ofObject:change:context:method in which the change object contains the corresponding value.

It is important to emphasize that KVO's callback will be invoked, that the property must be modified by the KVC method, and that this observer will not be notified if other methods of the calling class modify the property.

3. For the use of NSNotification, see http://blog.csdn.net/eduora_meimei/article/details/44198909

Difference:

Advantages of delegate:

1. Very strict grammar.All events to be heard must be clearly defined in the delegate protocol.

2. Compile warnings/errors will occur if one of the methods in delegate is not implemented

3. Agreement must be defined within the scope of controller

4. The control flow in one application is traceable and identifiable;

5. Multiple different protocols can be defined in one controller, each with a different delegates

6. There is no third party object that requires the communication process to be maintained/monitored.

7. The return value of the protocol method that can receive the call.This means that delegate can provide feedback to controller

Disadvantages:

1. Much code needs to be defined: 1. Protocol definition;2. delegate attribute of controller;3. Implement the delegate method definition in delegate itself

2. Be careful to change delegate to nil when releasing the proxy object.1If the setup fails, the call to free the object will result in memory crash

3. There are multiple delegate objects in an controller, and delegate complies with the same protocol, but it is still difficult to tell multiple objects the same event, but it is possible.

Advantages of notification:

1. It does not require much code to be written, so the implementation is simple.

2. For a notification, multiple objects can respond, that is, one-to-many is simple

3. controller can pass context objects (dictionary), which carry custom information about sending notifications

Disadvantages:

1. Notifications are not checked for proper handling by the observer at compile time;

2. When releasing the registered object, the registration needs to be cancelled at the Notification Center;

3. It is difficult to track the work applied and the control process while debugging.

4. Need a third party to favor the one to manage the relationship between controller and the observer object;

5. controller and the observer need to know the notification name, UserInfodictionary keys in advance.If these are not defined in the work area, there will be asynchronization;

6. controller cannot get any feedback from the observer after the notification is sent.

Advantages of KVO:

1. It can provide a simple method to synchronize two objects.For example: synchronization between model and view;

2. Ability to respond to changes in the state of objects other than those we create, i.e. internal objects, without changing the implementation of internal objects (SKD objects);

3. Ability to provide the latest and previous values of observed attributes;

4. Use key paths to observe attributes, so nested objects can also be observed.

5. Complete the abstraction of the observed object, as no additional code is required to allow the observed values to be observed

Disadvantages:

1. The attributes we observe must be defined using strings.Therefore, there will be no warnings or checks in the compiler;

2. Refactoring attributes will result in our observation code no longer being available;

3. Complex "IF" statements require that the object be observing multiple values.This is because all the observation code points in one way;

4. There is no need to remove the observer when the observer is released.

1. The efficiency is definitely higher for delegate than for NSNotification.

The delegate method is more direct than notification, and the most typical feature is that the delegate method tends to focus on the return value, which is the result of the delegate method.For example, -windowShouldClose:, you need to be concerned about whether yes or no is returned.Therefore, the delegate method often contains the word should.That is better than being my delegate. I'll ask you if you want to close the window?You need to give me an answer, and I'll use your answer to decide what to do next.On the contrary, the most important feature of notification is that I don't care about the recipient's attitude. I just let out the announcement. It's your thing if you accept or not, and I don't care about the result.So notification often uses the term did, such as NSWindowDidResizeNotification, so when an NSWindow object releases this notification, it does nothing and does not wait for the recipient to respond.

2. Differences between KVO and NSNotification:

Like delegate1, KVO and NSNotification also function as class-to-class communication, unlike delegate, which is 1) both responsible for notifying, leaving the rest unattended, so there is no return value;2) delegate is only 1-to-1, and these two can be 1-to-many.Both have their own characteristics.

Thank you for reading, I hope to help you, thank you for your support on this site!


Related articles: