KVC and KVO Brief introduction

Source: Internet
Author: User

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" >
    1. @interface Stockdata:nsobject {
    2. NSString * STOCKNAME;
    3. float price;
    4. }
    5. @end
    6. @implementation StockData
    7. @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
  1. -(void) Viewdidload
  2. {
  3. [Super Viewdidload];
  4. STOCKFORKVO = [[StockData alloc] init];
  5. [Stockforkvo setvalue:@"searph" forkey:@"StockName"];
  6. [Stockforkvo setvalue:@"10.0" forkey:@"price"];
  7. [Stockforkvo addobserver:self forkeypath:@"Price" options:nskeyvalueobservingoptionnew|  Nskeyvalueobservingoptionold Context:null];
  8. MyLabel = [[UILabel alloc]initwithframe:cgrectmake (100, 100, 100, 30)];
  9. Mylabel.textcolor = [Uicolor Redcolor];
  10. MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
  11. [Self.view Addsubview:mylabel];
  12. UIButton * b = [UIButton buttonwithtype:uibuttontyperoundedrect];
  13. B.frame = CGRectMake (0, 0, 100, 30);
  14. [B addtarget:self Action: @selector (Buttonaction) forcontrolevents:uicontroleventtouchupinside];
  15. [Self.view addsubview:b];
  16. }


3. When the button is clicked, call the Buttonaction method to modify the object's properties

[CPP]View Plaincopy
    1. -(void) buttonaction
    2. {
    3. [Stockforkvo setvalue:@"20.0" forkey:@"price"];
    4. }

4. Implementing a callback method

[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: ( void *) Context
    2. {
    3. if ([KeyPath isequaltostring:@"Price"])
    4. {
    5. MyLabel.Text = [Stockforkvo valueforkey:@"Price"];
    6. }
    7. }

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" >
    1. -(void) Dealloc
    2. {
    3. [Super Dealloc];
    4. [Stockforkvo removeobserver:self forkeypath:@"Price"];
    5. [Stockforkvo release];
    6. }
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

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

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.