About Kvo & KVC & Nsnotificationcenter Those things

Source: Internet
Author: User
Tags notification center

During the development of iOS, we often hear or use kvo,kvc,nsnotificationcenter and so on, but many times we may not know it well, let's learn more about their concepts, usage and relationships.

This blog is divided into the following several modules to introduce:

    • What is KVC?
    • What is KVO?
    • The relationship between KVC and KVO
    • KVC Collection Operators
    • What is Nsnotificationcenter?
    • Comparison of Nsnotificationcenter and KVO
    • Comparison of Nsnotificationcenter and delegate

Let's get down to the chase.

What is KVC?

1. KVC (key value encoding) concept:

Apple's Official Document Description: KVC (key-value-coding) is a mechanism that describes the properties of objects through string descriptions rather than by invoking access methods or directly using instance variables.

KVC is one of the implementation of the observer pattern in objective-c, which is defined in the form of a classification (informal protocol) in the NSObject, and from the point of view of the Protocol, defines a set of specifications and usage methods that developers can follow.

2. Use of KVC

In Cocoa's MVC framework, KVC is the bridge between Viewcontroler and model communication.

The basic methods of KVC are defined in the nskeyvaluecoding informal protocol, as shown in: (NSObject implements the protocol by default, which means that almost all objects in OC Support KVC operations).

@interface NSObject (nskeyvaluecoding)
-(Nullable ID) Valueforkey: (NSString *) key;
-(void) SetValue: (nullable ID) value Forkey: (NSString *) key;
-(Nullable ID) Valueforkeypath: (NSString *) KeyPath;
-(void) SetValue: (nullable ID) value Forkeypath: (NSString *) KeyPath;

KVC can be used to access object properties, one-to-one relational objects, one-to-many relational objects

    1. Access to object properties: It can also be a member variable of an object, a member variable is private or accessible, a property can be an object, or it can be a numeric type and struct, a non-object type parameter and a return value are automatically encapsulated into the Nsvalue alive NSNumber type.
      Valueforkey: Returns the value of the key associated with the receiver and, if there is no accessor or instance variable for the specified key, sends itself a VALUEFORUNDEFINEKEY: message, The default implementation of this method is to throw a nsundefinedkeyexception
    2. accessing objects through Relationships: Suppose the object person has a property address, the attribute address has a property city, and we can access City by person:

      [Person valueforkeypath:@ "address.city"];

      Valueforkeypath: Returns the value of the key path associated with the recipient, and receives a Valueforundefinekey: message for any object in the child family that does not follow KVC.

    3. Access to collection objects: can be mutable collections and immutable collections, and mutable collections are combined with KVO to enable the ability to batch update (multiple objects to be passed in).

      Dictionarywithvaluesforkeys: Retrieves the value of all the key associated with the receiver in the array, and the returned nsdictionary contains the values of all the keys in the array.

KVC can set the value of a property

The Setvalue:forkey is used to set the value of the associated key in the receiver to the specified value. In the implementation of this method, the value of Nsvalue is converted to a normal value and then assigned to the property.

KVV (key-value-validate) key value verification

-(BOOL) Validatevalue: (inout ID *) iovalue forkey: (NSString *) Inkey error: (Out nserror * *) Outerror;

What is KVO?
  1. The basic idea of the Observer pattern:

    The observer pattern is primarily the use of an object to manage all observer objects that depend on it, and to proactively notify the Observer object when its own state changes. The target object notifies the observer that it is usually implemented by invoking the interface method provided by each observation object. The Observer pattern is perfect for decoupling the target object from the Observer object.

  2. KVO Application Scenarios:

    When a particular property of an object changes, one or more objects need to be notified.

  3. KVO Use process:

    • Register and unregister

      KeyPath not nil
      -(void) Addobserver: (NSObject *) Observer Forkeypath: (NSString *) keypath options: (nskeyvalueobservingoptions) Options context: (Nullable void *) context ;
      -(void) Removeobserver: (NSOBJECT *) Observer Forkeypath: (NSString *) KeyPath;

    • Setting value

      [target setage:30];//setter
      [Target Setvalue:[nsnumber NUMBERWITHINT:30] forkey:@ "age"]; Setvalue:forkey

    • Handling change notifications

      Observers need to implement the category method named Nskeyvalueobserving to handle the notification of changes received

      -(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (Nsdictionary *) ch Ange context: (void *) context;

    When an observer needs to observe the same keypath of multiple objects, you can set the context to distinguish between different notifications.

  4. Property dependency

    Simply put, by observing the value of a key, to observe the changes of multiple properties, the object needs to implement the following methods.

    + (Nsset *) keypathsforvaluesaffectingaddress
    {
    Nsset *set = [Nsset setwithobjects:@ "FirstName", @ "LastName", nil];
    return set; This method makes it possible to establish a dependency between Key
    }
    To set a dependency between attributes
    -(NSString *) address
    {
    return [NSString stringwithformat:@ "%@%@", Self.province,self.street];
    }

The relationship between KVC and KVO

KVO is implemented based on KVC, and KVO only works when we call KVC to access the key value.

KVC Collection Operators (KVC set operator)
  1. KVC The concept of the set operator:

    The KVC collection operator allows you to execute a method in a collection by using the key path symbol "@" in the Valueforkeypath: method. Results can be returned or linked.

  2. KVC the type of the collection operator (according to the type of the return value):

    • Simple set Operator: The return value is NSString, NSNumber, or NSDate
    • Object operator: The return value is an array
    • Array and set operators: The return value is an array or a collection
  3. Simple collection operator

    • @count: Returns a NSNumber object that has a value of the total number of objects in the collection
    • @sum: First convert each object in the collection to a double type, and then calculate its total, Finally, a NSNumber object
    • with a value of this sum is returned @avg: first convert each object in the collection to a double type, then calculate its average, and finally return a NSNumber object
    • @max with a value of this sum: Use the Compare: method to determine the maximum value. So in order for it to work properly, all objects in the collection must support a comparison with another object
    • @min: As with @max, but the smallest value in the collection is returned.
    • Use Example:

      Products is an array with many objects in the array, and each object has a property of price.
      [Products valueforkeypath:@ ' @sum. Price]; The
      can use self as the keypath behind the operator to get a total value of an array or collection of NSNumber.
      [@[@1,@2] valueforkey:@ "@max. Self"];

  4. Object operator

    • @distinctUnionOfObjects: Gets the value of the property of each object in the array, puts it in an array, and returns it, which is weighed against the group.
    • @unionOfObjects: Same as @distinctunionofobjects, but not heavy.
    • Use Example:

      Person *lilei = [[Person alloc] init];
      Lilei.name = @ "Lilei";
      Person *hanmeimei = [[Person alloc] init];
      Hanmeimei.name = @ "Hanmeimei";
      Nsarray *array = @[lilei, Hanmeimei];
      NSLog (@ "Array is%@", [Array valueforkeypath:@ "@distinctUnionOfObjects. Name"]);
      Output:
      2015-11-10 16:08:07.977 testpro[49746:521302] array is (
      Lilei,
      Hanmeimei
      )

  5. Array and set operators

    • @distinctUnionOfArrays: Gets the value of the property of each object in each array in the array, puts it in an array, and returns it, repeating the group.
    • @unionOfArrays: With @distinctunionofarrays, but not heavy.
    • @distinctUnionOfSets: Gets the value of the property of each object in each collection in the collection, placed in a collection, and returned.
    • Examples of Use:

      Person *lilei = [[Person alloc] init];
      Lilei.name = @ "Lilei";
      Person *hanmeimei = [[Person alloc] init];
      Hanmeimei.name = @ "Hanmeimei";
      Nsarray *array = @[lilei, Hanmeimei];
      NSLog (@ "Array is%@", [@[array,array] valueforkeypath:@ "@unionOfArrays. Name"]);
      The output is:
      2015-11-10 16:51:26.137 testpro[50404:556930] array is (
      Lilei,
      Hanmeimei,
      Lilei,
      Hanmeimei
      )

What is Nsnotificationcenter?
  1. The concept of notification hubs:

    A notification hub is a subsystem of the FOUNDATION framework and an observer pattern that broadcasts messages (that is, notifications) to all objects in an application that are registered as an event watcher, and can be used when communicating between classes.

    • Note that when you receive the message, you do not want to receive the message again, remove the observer. Usually remove when the class is destroyed.
  2. The two classes that make up the notification hub:

    • Nsnotificationcenter: There is only one way to get nsnotificationcenter, namely [Nsnotificationcenter Defaultcenter], And Nsnotificationcenter is a singleton mode, once created, this notification center object will always exist in the life cycle of an application.
    • Nsnotification: This is the carrier of the message, through which the message content can be passed to the observer.
  3. Usage flow for notification hubs:

    • Registration NOTICE: Nsnotificationcenter The registered observer is interested in an event (named after a string) and the Selector or Block that executes when the event is triggered.

      [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (notificationmethod:) name:@ " Notificationname "Object:nil";
      Parameter comment:
      First parameter (self): the object that is responsible for listening
      The second parameter (@selector (NotificationMethod:)): The method that the listener needs to execute after receiving the notification.
      The third parameter (@ "Notificationname"): The name of the notification and the only indication of the notification, which is the compiler to find the notification.
      The fourth parameter (nil): The last argument is a response to the event that the sender object is emitted, and nil indicates the event that accepts all senders.

    • Send notification: Send a message manually

      [[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Notificationname" object:test userInfo:@{@ "key": @ " Value "}];
      Parameter comment:
      First parameter (@ "Notificationname"): The name of the notification, which must match the name of the subsequent receive notification
      Second parameter (test): A Parameter object that can be passed
      The third parameter (@{@ "key": @ "Value"}): Information that can be passed, related to the notification,

    • Remove notification: Remove the notification when the viewer no longer receives the message

      -(void) dealloc
      {
      Remove the specified notification, or it will cause a memory leak
      [[Nsnotificationcenter Defaultcenter] removeobserver:self name:@ "happyvaluenotification" object:nil];
      Remove all Notifications
      [[Nsnotificationcenter Defaultcenter] removeobserver:self];
      }

Comparison of Nsnotificationcenter and KVO
    1. Same point:
      • The realization principle of nsnotificationcenter and KVO is the Observer pattern. For listening operations
    2. Different points:
      • KVO is only used to listen to the changes in the value of the property, the operation is system control, we can't control, we can only control the monitoring operation, similar to the system sent in Android broadcast.
      • We can control the notification of sending and listening, and can send a notification anywhere at any time. Similar to the broadcasts that developers themselves send on Android.
      • Notifications are more widely used than KVO
      • Notifications require an object that sends notification, typically Notificationcenter, to notify the Observer. KVO is the direct notification to the observer, and the logic is very clear, the implementation of simple steps.
      • In short, the KVO operation is not notification flexible. But KVO also has its own advantages, such as can record the old and new values, notification is more troublesome, so in the use of the specific problem of the specific analysis, the general monitoring of the value of the property changes, it is best to use KVO.
Comparison of Nsnotificationcenter and delegate

The notification can achieve a greater span of communication than DELEAGTE, which can communicate with two non-referential two objects, that is, the event issuer and the responder can have no coupling relationship.

About Kvo & KVC & Nsnotificationcenter Those things

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.