IOS_KVC and KVO

Source: Internet
Author: User

Directory: First, KVC Second, KVO I. Mechanism of KVC 1, KVC Brief description KVC is the abbreviation for keyvaluecoding (key-value pair), which is a mechanism that can access class attributes (instance variables) directly through the string's name (key). Instead of being accessed by invoking a setter, getter method. KVO is one of the key technologies based on KVC implementation. 2, the key method of using method is defined in: Nskeyvaluecodingprotocol. KVC supports class objects and built-in basic data types. Common methods of KVC:-(ID) Valueforkey: (NSString *) key;//get-(void) SetValue: (ID) value Forkey: (NSString *) key;//settings  The Valueforkey method reads the properties of the object according to the value of the key, Setvalue:forkey: The property of the object is written according to the value of the key.    For example: [Person setvalue:@ "Tom" forkey:@ "name"]; NSString *name = [Person valueforkey:@ "name"];
#import <Foundation/Foundation.h>@interface person:nsobject{    *_name;    Nsinteger _age;     *_wife;} @end
#import"ViewController.h"#import"Person.h"@interface Viewcontroller () @end @implementation Viewcontroller- (void) viewdidload {[Super viewdidload]; //Creating ObjectsPerson *person =[[Person alloc]init]; //use KVC to store data members of an object[Person SetValue:@"Tom"Forkey:@"_name"]; [Person setvalue:@ -Forkey:@"_age"]; NSLog (@"person:%@", person); //fetching data members of an objectNSString *name = [Person Valueforkey:@"_name"]; Nsinteger Age= [[Person Valueforkey:@"_age"]integervalue]; NSLog (@"KVC mode access: Name:%@,age:%ld", Name,age); } @end

If you need to print an output object, you also need to override the Descaprition method of the person class.

" Person.h " @implementationPerson-(NSString *) description{    return [NSString stringWithFormat: @" name:%@,age:%ld " , _name,_age];} @end

3, the use of extended KVC

  @interface Book:nsobject@property (copy,nonatomic) nsstring  *bookname. m file for @endBook class #import      @implementation book -( NSString *) description{ return  [ NSString stringwithformat:@ "  " ,_bookname";} @end  
<Foundation/Foundation.h>**"Person.h"@ ImplementationPerson-(NSString *) description{    return [NSString stringWithFormat: @" name:%@,age:%ld " , _name,_age];} @end

Finally, the implementation file.

#import"ViewController.h"#import"Book.h"#import"Person.h"@interface Viewcontroller () @end @implementation Viewcontroller- (void) viewdidload {[Super viewdidload]; person*P1 =[[Person alloc]init]; [P1 setValue:@"Tom"Forkey:@"name"]; [P1 setvalue:@ atForkey:@" Age"]; Book*book1 =[[Book Alloc]init]; Book1.bookname=@"IPhone"; P1.book=Book1; person*P2 =[[Person alloc]init]; [P2 SetValue:@"Jerry"Forkey:@"name"]; [P2 setvalue:@ atForkey:@" Age"]; Book*book2 =[[Book Alloc]init]; Book2.bookname=@"IOS"; P2.book=Book2; NSLog (@"%@%@", P1,[P2 Valueforkeypath:@"name"]); Nsarray*person =@[p1,p2]; NSLog (@"%@", person); Nsarray*arraym = [Person Valueforkeypath:@"Book.bookname"]; NSLog (@"%@", Arraym);} @end
two, KVO mechanism                               &N Bsp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                 1, KVO Brief introduction KVO, namely: Key-value observing, it provides a mechanism, when the specified object's properties are modified, the object will accept the notification.  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. 2, the use of the system framework has been supported KVO, so the programmer is very simple to use. Use steps: (1) Register the properties of the object to be observed AddObserver:forKeyPath:options:context: (2) Implement ObserveValueForKeyPath:ofObject:change:context : Method, this method is automatically called when the observed property changes (3) Unregister observation RemoveObserver:forKeyPath:context:
#import <Foundation/Foundation.h>@interface person:nsobject{    *_name;} @end
" Person.h " @implementation Person // notification of acceptance of changes to the observed person -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)object Change: (nsdictionary *) Change context: (void *) context{    NSLog (@ "%@,%@,%@,%@  ", KeyPath,object, Change,context);} @end

Add a stock class that allows person to monitor the price of a stock as an observer.

#import <Foundation/Foundation.h>@interface stock:nsobject{    *_name;     float _price;} @end

Implement the file contents:

#import"ViewController.h"#import"Person.h"#import"Stock.h"@interface Viewcontroller () @property (strong,nonatomic) person*Person ; @property (strong,nonatomic) Stock*stock; @end @implementation Viewcontroller- (void) viewdidload {[Super viewdidload]; //Create observerSelf.person =[[Person alloc]init]; [Self.person SetValue:@"Tom"Forkey:@"_name"]; //Create stockSelf.stock =[[Stock alloc]init]; [Self.stock SetValue:@"SXT"Forkey:@"_name"]; [Self.stock setvalue:@1.2Forkey:@"_price"]; //Set Observer[Self.stock AddObserver:self.person Forkeypath:@"_price"Options:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:@"Add"];}//Click the button to add 1 to the stock price-(Ibaction) buttonclicked: (UIButton *) sender{floatPrice = [[Self.stock valueforkey:@"_price"]floatvalue]; [Self.stock setvalue:@ ( price+1.0) Forkey:@"_price"];}-(void) dealloc{//Delete Viewer[Self.stock RemoveObserver:self.person Forkeypath:@"_price"];} @end

IOS_KVC and KVO

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.