Im registering an observer for on of my class named myClassA ( subclass of uiview ) from one of my class named UIScrollView(Sample)( a category for uiscroll view )
@implementation UIScrollView (myClass)
// Register an observer
- (void)registerAsObserver {
[self addObserver:[self getMyClassA] forKeyPath:@"notification" options:NSKeyValueObservingOptionNew context:nil];
}
In myClassA
@implementation myClassA
- (id)initWithFrame:(CGRect)frame {
if(self = [super initWithFrame:frame]) {
// Initialization goes here
}
return self;
}
#pragma mark - Receive notification of change
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
CGPoint newPoint = [[change objectForKey:NSKeyValueChangeNewKey] CGPointValue];
if ( [keyPath isEqualToString:@"notification"] ) {
[self doSomething:newPoint];
}
}
However, it seems to be that myClassA is not receiving any notification from UIScrollView(myClass)
. After google it, i found out that the reason is the keyword forKeyPath. If i change it to contentOffset
, everything works like charm.
Did a quick research at here but still dont understand why.
See Apple's basic documentation on KVO:
With KVO, one object can observe any properties of another object
Well, UIScrollView has a contentOffset
property. So it is key value coding compliant for contentOffset
. So you can observe changes to that property, and that is what you are asking to do if you set the key path to contentOffset
.
UIScrollView has no notification
property, so its notification
property can never change, so there is nothing to observe if you set the key path to notification
.
Here's the explanation from my book: