Read so many blogs. The description is so complex, in fact KVC is very simple, not described so complex, so write a simple easy to understand the post, cut into the text:
The 1.KVC layer is manipulated by the runtime method and value
For example, the following line KVC code:
[Sit setvalue:@ "sitename" forkey:@ "name"];
will be processed by the compiler:
Sel sel = Sel_get_uid ("Setvalue:forkey:");
IMP method = Objc_msg_lookup (Site->isa,sel);
Method (site, SEL, @ "sitename", @ "name");
The first two steps are to find the method through RT, the last step to update the value;
2.KVO is based on KVC added a message notification, observer mode;
Two basic methods of 3.KVB
1: Add observer for object Observer
AddObserver:forKeyPath:options:context:
2: Observer observer processing function for receiving information
ObserveValueForKeyPath:ofObject:change:context:
Here's how to use demo
1. Operate the attribute/variable directly in VC (not recommended coupling degree is not good)
@property (Nonatomic,strong) NSString *str1;
Join in Viewdidload:
[Self addobserver:self forkeypath:@ "str1" options:nskeyvalueobservingoptionnew context:nil];//First step
[Self setvalue:@ "grass mud Horse Kvo" forkey:@ "str1"];//Step Two
callback method
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{
if ([KeyPath isequaltostring:@ "Count"]) {
NSLog (@ "Count:%@", [Change valueforkey:@ "new"]);
}
if ([KeyPath isequaltostring:@ "str1"]) {
NSLog (@ "str1:%@", [Change valueforkey:@ "new"]);
}
}
In the first step add the registration element @ "STR1", and then the second step changes its value, at which point the third callback method responds;
2. Custom Class Oberserclass
#import <Foundation/Foundation.h>
@interface Oberserclass:nsobject
@property (nonatomic,assign) int count;
@end
#import "OberserClass.h"
@implementation Oberserclass
@end
Simply add a property and do nothing. Then add the following code to the Viewdidload:
CLS = [[Oberserclass alloc]init];//cls must be a member variable, cannot be a local variable
[CLS addobserver:self forkeypath:@ "Count" Options:nskeyvalueobservingoptionnew Context:nil];
[CLS setvalue:@ "456" forkey:@ "Count"];
Execute to the last step Observevalueforkeypath will receive a notification processing @ "Count"
3. Custom class Internal processing
Unlike the second one, add the following code to the @implementation:
-(void) SetCount: (int) count{
_count = count;
[Self addobserver:self forkeypath:@ "Count" Options:nskeyvalueobservingoptionnew Context:nil];
}
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) context{
if ([KeyPath isequaltostring:@ "Count"]) {
NSLog (@ "Count is:");
}
}
@end
Demo:kvcdemo
IOS KVC/KVO/KVB