What's wrong with this observeValueForKeyPath:ofObject:change:context: implementation?

后端 未结 2 1278
终归单人心
终归单人心 2021-02-05 14:45

In my UIScrollView subclass, I\'m observing frame changes:

[self addObserver:self forKeyPath:@\"frame\" options:0 context:NULL];

My obser

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 15:41

    You should add a context value when you add the observer. In your -observeValueForKeyPath method, check the context parameter. If it is not the context you passed when you added the observer, then you know this message is not intended for your subclass, and you can safely pass it on to the superclass. If it is the same value, then you know it's intended for you, and you should not pass it on to super.

    Like this:

    static void *myContextPointer;
    
    - (void)addSomeObserver {
        [self addObserver:self forKeyPath:@"frame" options:0 context:&myContextPointer];
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        if (context != &myContextPointer) {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
        else {
            // This message is for me, do whatever I want with it.
        }
    }                                  
    

提交回复
热议问题