KVC (keyvaluecoding) "Key-value-code" is a mechanism for accessing class instance variables directly through the string's name (key).
KVC can be used to access and set the value of an instance variable.
Setting mode: [Self setvalue:aname forkey:@ "name"]
[Self setvalue:aname forkeypath:@ "Person.name"]
Access mode: astring = [self valueforkey:@ "name"]
astring = [Self valueforkeypath:@ "person.name"]
1 Main function Contents2Person *xiaoli =[[Person alloc]init];3 //Book *book = [[book Alloc]init];4 //[book Addmyobserver];5 6[Xiaoli Setbookname:@"the dream of Red mansions"Andprice: -];7[Xiaoli Setbookname:@""Kingdoms""Andprice:56.5];8[Xiaoli Setbookname:@""Outlaws of the Marsh""Andprice:68.8];9[Xiaoli Setbookname:@""Journey to the Monkey""Andprice:75.2];Ten OneNsarray *array = [Xiaoli valueforkeypath:@"Bookarray"]; A - for(Book *bookinchArray) - { the -NSLog (@"%@ %@", [book Valueforkey:@"BookName"],[book Valueforkey:@" Price"]); - } - + - + #import<Foundation/Foundation.h> A #import "Book.h" at - @interfacePerson:nsobject - { -NSString *name; -Nsmutablearray *Bookarray; -Book *Abook; in } - to- (void) Setbookname: (NSString *) BookName Andprice: (float) Price; + - @end the * $ Panax Notoginseng - #import "Person.h" the #import "Book.h" + A @implementation Person the +- (void) Setbookname: (NSString *) BookName Andprice: (float) Price - { $ //if Bookarrar is not initialized, initialize the $ if(!Bookarray) { -Bookarray =[[Nsmutablearray alloc]init]; - } the -Book *book =[[book Alloc]init];Wuyi the //start listening to changes in the title - [book Addmyobserver]; Wu -[Self Setvalue:book forkey:@"Abook"]; About[Self setvalue:bookname Forkeypath:@"Abook.bookname"]; $ - //the price is encapsulated into NSNumber data assigned to BookName, which is automatically converted to float when the bookname is read. -NSNumber *price1 =[NSNumber Numberwithfloat:price]; -[Self Setvalue:price1 Forkeypath:@"Abook.price"]; A + //to load a book into an array the [Bookarray Addobject:abook]; - $ } the the @end the the - in the #import<Foundation/Foundation.h> the About @interfaceBook:nsobject the the { theNSString *BookName; + floatPrice ; - } the Bayi- (void) Addmyobserver; the the @end - - the the the #import "Book.h" the - @implementation Book the the- (void) Addmyobserver the {94 //Registering Listener Objects the[Self addobserver:self Forkeypath:@"BookName"options:nskeyvalueobservingoptionnew Context:nil]; the //Observer the }98 About //Listener Property Instance value changes -- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (nsdictionary *) Change context: (void*) Context101 {102NSLog (@"bookname%@", change);103 }104 the- (void) Dealloc106 {107 //Remove Listener108[Self removeobserver:self Forkeypath:@"BookName"];109 [Super Dealloc]; the }111 the 113 @end
Object-c KVC KVO (with attributes array, book object, array loaded book object)