IOS KVC & KVO

Source: Internet
Author: User

IOS KVC & KVO

Key Value CodingKey Value Coding is a standard component of cocoa, which allows us to access the property by name (key) without having to invoke the explicit property accssor, as we have a property called Foo, We can get Foo to access it directly, we can also use KVC to complete the [Object valueforkey:@ "foo"], some students will ask, what is the benefit of doing this? The main benefit is to reduce the amount of code we have. Let's take a look at a few examples and understand the usage and benefits of KVO, assuming such a class is called people,
    1. @Interface People:nsobject
    2. @property (nonatomic, strong) NSString *name;
    3. @property (nonatomic, strong) NSNumber *age;
    4. @end
Scene 1,apple An example of the official website, when we need to count a lot of people, each row is an instance of a person, and there are 2 columns of properties, name, age, which we can do,
  1. -(ID) TableView: (Nstableview *) TableView
  2. Objectvaluefortablecolumn: (ID) column row: (Nsinteger) Row {
  3. People *people = [Peolearray objectatindex:row];
  4. if ([[column identifier] isequaltostring:@"name"]) {
  5. return [people name];
  6. }
  7. if ([[column identifier] isequaltostring:@"age"]) {
  8. return [people age];
  9. }
  10. //And so on.
  11. }
We can also use KVC to help us simplify these if, because name, age is actually the property, we can directly through the key to access, so after finishing is
    1. People *people = [Peoplearray objectatindex:row];
    2. return [People valueforkey:[column Identifier]];
Scenario 2, we have a server, a server API (Listpeople??), will return our JSON format an array containing such dict{name:xx, age:xx} such data, We want to use these dict data to construct our people, and it is usually our practice to write a static factory method for our people class to handle dict, remove the data from the Dict, and then create an empty people object. Then set the property in turn. However, when such a similar people with the server to interact with the class, we will have to add such a wrapper for each class, whether there is a simple way to set such a property, of course, our KVC.
    1. -(ID)  initwithdictionary: (nsmutabledictionary*)  jsonObject 
    2. { 
    3.     if ((Self = [super init]))  
    4.     { 
    5.         [SELF INIT]; 
    6.         [self setValuesForKeysWithDictionary:jsonObject];  
    7.     } 
    8.      RETURN SELF; 
    9. } 
Setvaluesforkeyswithdictionary, will for us and dictionary key name of the same class Proerty set on the Dict key corresponding value, is not very convenient ah, but some students have to ask If some key in JSON is not the same as the property name of object, or some of the fields returned by the server are OBJC reserved words such as "id", "description", etc., we also want to also map dict to object, At this point we need to use the Setvalue:forundefinedkey, because if we do not deal with these undefined Key, or setvaluesforkeyswithdictionary will throw an exception.
    1. -  (void) SetValue: (ID) Value forundefinedkey: ( nsstring *) key 
    2. { 
    3.      if ([Key isequaltostring:@
    4.         self.name = value; 
    5.     if ([key isequaltostring:@ "agexxx"])  
    6.         self.age = value; 
    7.     else 
    8.          [super setvalue:value forkey:key]; 
    9. } 
So as long as this method is overloaded, you can deal with the key that cannot match the property, the default implementation is to throw a nsundefinedkeyexception, and the classmate asked if the server returned people with embedded JSON ( such as Products{product1{count:xx, Sumprice:xx}}, product2{} ...), what to do, you can convert this embedded JSON into our client's product class, Of course, this time you need to overload setvalue:forkey, processing "products" this key, wrapper it into the class we need
    1. -(void)  setvalue: (ID) Value forkey: (nsstring  *) key 
    2. { 
    3.   if ([key  Isequaltostring:@ "products"])  
    4.   { 
    5.     for (nsmutabledictionary *productdict in value)  
    6.     { 
    7.       prodcut *product = [[product alloc]  initwithdictionary:prodcutdict]; 
    8.       [self.products  addobject:product]; 
    9.     } 
    10.   } 
    11. } 
In Scenario 3, we need to capitalize the first letter of the name of the people in an array and put the new name into the new array, which is usually done by traversing the entire array and then extracting the name of each people, calling Capitalizedstring The new string is then added to the new array. With the KVC, there is a new approach:
    1. [Array valueforkeypath:@"name.capitalizedstring"]
  We see Valueforkeypath, why use Valueforkeypath, not valueforkey, because Valueforkeypath can pass the relationship, for example, here is the name of each people property of the String Capitalizedstring property, and Valueforkey can not pass such a relationship, so for dict inside the dict, we can only use Valueforkeypath. Here we also see KVC for Array (set), do a special processing, not simple operation collection, but for these collection inside the elements to operate, the same KVC also provide more operations, such as @sum these for collection, Interested students can go to use the next.   Scene 4, when we execute nsarray *products = [People valueforkey:@ "products"], we want [people products], but people has no such method, What will KVC bring to us?   First will look for getprodcuts or products or isproducts, in this order to find, the first found will return and then go to find countofproducts and either Objectinproductsatindex:or productsatindexes, if found, will find Countofproducts and Enumeratorofproducts and memberOfProducts This 2 method has been found, KVC will return to us an agent of the Nskeyvaluearray, for our subsequent operations (ADDPRODUCT and the like).   If there is a variable called products, isproducts, or isproducts, KVC will use such a variable directly, if you feel that the direct use of such a variable is to destroy the encapsulation, can prohibit such behavior occurs, overload + accessinstancevariablesdirectly, returns No.   Simply put, Valueforkey, will bring us a proxy array, if we implement certain methods, the appeal of these methods is only for Nsarray, for mutable collection, we also need to provide otherThe implementation of the method is only OK.  Key Value ObservingKey Value observing, as the name implies is a observer mode for monitoring property changes, KVO and nsnotification have a lot of similar places, with AddObserver:forKeyPath:options : Context: Go to start observer, with REMOVEOBSERVER:FORKEYPATH:CONTEXT to stop Observer, callback is Observevalueforkeypath:ofobject: Change:context:.
  1. -(void) removeobservation {
  2. [Self.object removeobserver:self
  3. ForKeyPath:self.property];
  4. }
  5. -(void) addobservation {
  6. [Self.object addobserver:self ForKeyPath:self.property
  7. options:0
  8. Context: (__bridge void*) self];
  9. }
  10. -(void) Observevalueforkeypath: (NSString *) KeyPath
  11. Ofobject: (ID) object
  12. Change: (nsdictionary *) change
  13. Context: (void *) Context {
  14. if ((__bridge id) context = = self) {
  15. //Handle only the property updates with our current class
  16. }
  17. else {
  18. [Super Observevalueforkeypath:keypath Ofobject:object
  19. Change:change Context:context];
  20. }
  21. }
For KVO, all we have to do is simply update our property data,don't need to be as concerned as nsnotificationcenter whether someone is listening to your request, and if no one listens to what to do, all Addobserver, Removeobserver, callback are things that you want to listen to the class of your property. Once a project, with Nsnotificationcenter Post notification in a network callback inside, but this time because the earliest Addobserver class was released, Then the generated Addobserver class, received the last observer to listen to the event, so caused the error, then the solution is to do a unique Addobserve key, not 2 times the Addobserver key is the same, But with the KVO, we can also use KVO to complete, when the Addoberver object remove, there will be no such callback is called. KVO provides us with less code, andbetter than nsnotification, you don't need to change the class you're observing, it's always the people who watch you do things. But there's something wrong with KVO, 1. If there is no observer monitoring key path, RemoveObsever:forKeyPath:context: This key path, will be crash, unlike Nsnotificationcenter Removeobserver. 2. It's hard for you to find out who is listening to your property's changes, and it's more troublesome to find them. 3. For a complex and highly relevant class, it is best not to use KVO, delegate or notification way to be relatively concise.SummaryTry to use KVC can greatly reduce the amount of our code, when encountered property, you can think of whether you can KVC to help me, whether you can use KVC to refactor the code, when the need to join the Observer mode, you can consider KVO, in the high-performance observer inside, KVO will give us a good help.

IOS KVC & 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.