KVO
QQ Group of APP development technology: 347072638
One, overview
KVO, Key-value Observing, provides a mechanism for the object to receive notification when the properties of the specified object have been modified. Simply put, the KVO will automatically notify the appropriate observer when the property of the observed object has been modified each time it is specified.
Second, how to use
The system framework already supports KVO, so programmers are very easy to use.
1. Register, specify the attributes of the viewer,
2. Implementing a callback method
3. Removal of observations
Three, example:
Suppose a scenario where the price of a stock is displayed on the current screen, and when the stock price changes, the real-time display updates its price.
1. Define Datamodel,
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- @interface Stockdata:nsobject {
- NSString * STOCKNAME;
- float price;
- }
- @end
- @implementation StockData
- @end
2. Define this model as the controller's property, instantiate it, listen to its properties, and display it in the current view
[CPP]View Plaincopy
- -(void) Viewdidload
- {
- [Super Viewdidload];
- STOCKFORKVO = [[StockData alloc] init];
- [Stockforkvo setvalue:@"searph" forkey:@"StockName"];
- [Stockforkvo setvalue:@"10.0" forkey:@"price"];
- [Stockforkvo addobserver:self forkeypath:@"Price" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold Context:null];
- MyLabel = [[UILabel alloc]initwithframe:cgrectmake (100, 100, 100, 30)];
- Mylabel.textcolor = [Uicolor Redcolor];
- MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
- [Self.view Addsubview:mylabel];
- UIButton * b = [UIButton buttonwithtype:uibuttontyperoundedrect];
- B.frame = CGRectMake (0, 0, 100, 30);
- [B addtarget:self Action: @selector (Buttonaction) forcontrolevents:uicontroleventtouchupinside];
- [Self.view addsubview:b];
- }
3. When the button is clicked, call the Buttonaction method to modify the object's properties
[CPP]View Plaincopy
- -(void) buttonaction
- {
- [Stockforkvo setvalue:@"20.0" forkey:@"price"];
- }
4. Implementing a callback method
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: ( void *) Context
- {
- if ([KeyPath isequaltostring:@"Price"])
- {
- MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
- }
- }
5. Increased observation and cancellation of observations are in pairs, so it is necessary to remove the observer at the last
[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
- -(void) Dealloc
- {
- [Super Dealloc];
- [Stockforkvo removeobserver:self forkeypath:@"Price"];
- [Stockforkvo release];
- }
Four, summaryKvo This encoding method is very simple to use, it is suitable with Datamodel modified, the uiview caused by the change in this case, as the above example, when the value of the property changed, the listener will be immediately notified.
KVC
One, overview
KVC is the abbreviation for keyvaluecoding, which is a mechanism for accessing class properties directly through the string's name (key). Instead of being accessed by invoking a setter, getter method.
KVC is a key technology when using KVO, Core Data, Cocoabindings, AppleScript (Mac support).
Second, how to use
Key methods are defined in: Nskeyvaluecodingprotocol
KVC supports class objects and built-in basic data types.
Get Value
Valueforkey:, the name of the incoming NSString property.
Valueforkeypath:, the path of the incoming NSString property, xx.xx form.
Valueforundefinedkey its default implementation is to throw an exception, you can override this function to do error handling.
Modifying Values
Setvalue:forkey:
Setvalue:forkeypath:
Setvalue:forundefinedkey:
Setnilvalueforkey: Called when Nil is set on a non-class object property, the exception is thrown by default.
case of a one-to-many relationship member
Mutablearrayvalueforkey: Ordered one-to-many relationship member Nsarray
Mutablesetvalueforkey: Unordered one-to-many relationship member Nsset
Three, example:
1.1. Person class
2. @implementation person
3. @synthesize name,age;//property name will be monitored
4.-(void) changename
5. {
6. [Email protected] "changename directly";
7.}
8. @end
9.
10.
One. 2.PersonMonitor class monitors the Name property
@implementation Personmonitor
13.
-(void) Observevalueforkeypath: (NSString *) keypath
Ofobject: (ID) object
Change: (nsdictionary *) change
. Context: (void *) context
18. {
if ([KeyPath isequal:@ "name"])
20. {
NSLog (@ "Change happen, old:%@ new:%@", [Change Objectforkey:nskeyvaluechangeoldkey],[change Objectforkey:nske Yvaluechangenewkey]);
22.}
23.}
@end
25.
26.
27.3 Test Code
28.
29.//Initialize monitored objects
Person *p =[[person alloc] init];
31.//Monitor Object
Personmonitor *pm= [[Personmonitor alloc]init];
[P addobserver:pm forkeypath:@ "name" Options: (Nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold) Context:nil];
34.
35.//Pre-test data
NSLog (@ "P.name is%@", p.name);
37.
38.//Through SetValue method, Personmonitor's monitoring will be called
[P setvalue:@ "name KVC" forkey:@ "name"];
40.
41.//View the value after setting
NSLog (@ "p name Get by KVC is%@", [P valueforkey:@ "name"]);
43.
44.//Effect and is consistent through SetValue
[Email protected] "name change by. Name=";
46.
47.//change name by person's own function
[P changename];
49.
50. The result is
51. Output
2011-07-03 16:35:57.406 cocoa[13970:903] P.name is name
2011-07-03 16:35:57.418 cocoa[13970:903] change happen, Old:name New:name KVC
2011-07-03 16:35:57.420 cocoa[13970:903] p name Get by KVC is name KVC
2011-07-03 16:35:57.421 cocoa[13970:903] change happen, Old:name KVC new:name change by. name=
56. The last modification is a direct modification, so no notification is generated.
Four, summaryKVO/KVC This encoding method is very simple to use, it is suitable with Datamodel modified, the uiview caused by the change in this case, as the above example, when the value of the property changed, the listener will be immediately notified.
KVC and KVO Brief introduction