Lightweight kvo[Translation]

Source: Internet
Author: User

In this article, I will implement a simple KVO class of my own, I think KVO is very good, but for most of my usage scenarios, there are two problems: 1. I do not like to ObserveValueForKeyPath:ofObject:change:context: In the method of the KeyPath value to do scheduling, when observe more objects, will make the code messy and confusing. 2. You must manually register and delete an observer, if you can do it automatically. So, let's start this implementation. This is the first time I've seen this in the Thobserversandbinders project, and this article only describes what it's doing and simplifies it. First, we define our class, the class name of our helper class is observer:
    1. @interface observer : nsobject 
    2. +  (instancetype) Observerwithobject: (ID) object 
    3.                              keypath: (nsstring*) keypath 
    4.                               target: (ID) target 
    5.                             selector: (SEL) selector; 
    6. @end  
The class method of the Observer class has four parameters, each parameter is self-explanatory, I choose to use Target/action mode, of course, you can use block, but that would need to do weakself/strongself conversion, you know, Generally speaking, it's better to do it in a split. What we do is set the KVO in the initialization method and remove it in the Dealloc method. This means that once the observer object is retain, we have an observer, and the following code is taken from one of my viewcontroller:
  1. Self.usernameobserver = [Observer observerWithObject:self.user
  2. keypath:@"Name"
  3. Target:self
  4. Selector: @selector (usernamechanged)];
Put this observer object as a property in the Viewcontroller to ensure that it is retain, once our Viewcontroller is released, it will be set to stop the observation of Nil,observer. In this implementation, it is important to use a weak reference to point to the observed object and the Observer (target), and if one of the two is nil, we stop sending the message to the Observer.
    1. @Interface Observer ()
    2. @property (nonatomic, weak) ID target;
    3. @property (nonatomic) SEL selector;
    4. @property (nonatomic, weak) ID observedobject;
    5. @property (nonatomic, copy) nsstring* KeyPath;
    6. @end
The KVO notification is set in the initializer, and it is necessary to use self as the context if we have a subclass that also adds similar observers.
    1. -(ID) Initwithobject: (ID) object keypath: (nsstring*) KeyPath target: (ID) Target selector: (SEL) Selector
    2. {
    3. if (self) {
    4. Self.target = target;
    5. Self.selector = selector;
    6. Self.observedobject = object;
    7. Self.keypath = KeyPath;
    8. [Object addobserver:self Forkeypath:keypath options:0 context:self];
    9. }
    10. return self;
    11. }
Once the observer has changed, we notify the Observer (target) if it still exists:
  1. -(void) Observevalueforkeypath: (nsstring*) KeyPath ofobject: (ID) object change: (nsdictionary*) Change context: ( void*) Context
  2. {
  3. if (context = = self) {
  4. ID strongtarget = Self.target;
  5. if ([Strongtarget RespondsToSelector:self.selector]) {
  6. #pragma clang diagnostic push
  7. #pragma clang diagnostic ignored "-warc-performselector-leaks"
  8. [Strongtarget PerformSelector:self.selector];
  9. #pragma clang diagnostic pop
  10. }
  11. }
  12. }
Finally, remove the Observer object in the Dealloc method:
    1. -(void) Dealloc
    2. {
    3. ID strongobservedobject = Self.observedobject;
    4. if (strongobservedobject) {
    5. [Strongobservedobject removeobserver:self ForKeyPath:self.keyPath];
    6. }
    7. }
That's the whole stuff. There are plenty of places to expand, like add block support, or trick I prefer: Add love again. A convenient construction method is used to invoke the action directly for the first time. However, what I think is to show the core of the technology, you can adjust it according to your own needs. The advantage of this technique is that you do not need to remember too many things when using KVO, just retain live observer objects, and then try to set nil in the finished test, the rest will be completed automatically. The original author is the founder of Chris Eidhof,objc.io. Address: Lightweight Key-value Observing Source: code Craftsman http://www.cocoachina.com/industry/ 20131106/7303.html

Lightweight kvo[Translation]

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.