What to use as a key path in KVO?

I have a view controller with a view that changes (for example), and I would like to watch the frame of any view that self.view is set to. Is there a difference between:

[self.view addObserver:self forKeyPath:@"frame" options:0 context:nil]; 

and

 [self addObserver:self forKeyPath:@"view.frame" options:0 context:nil]; 

For the second, if the view changes will receive messages when the new view frame changes, or will it only send messages if the view frame that was set when the observer was added?

Is there a way to observe changes in a frame property, even if the view controller's view changes after adding an observer?

+6
source share
2 answers

Use the second way. @"view.frame" will notify you of a frame change, even when the "view" itself is changed. Cocoa will automatically add observers for each object in the KeyPath keychain (which means that every element in keyPath must be KVO-compatible).

+7
source

You asked if there is a difference between the two. The answer is yes, there is a difference between them:

First

Saying "I'm as a point of view," I add an observer named self (aka) viewControllerObject if you called it in viewController.m whenever a property called "frame" changes.

Second

Says "me like a ViewController". I add selfAsAnObserver whenever a KeyPath called "view.frame" changes.

Since each observer must implement

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 

In this case, you will not notice much difference, because you added the viewController as an observer in any of the methods above, but it will matter when you are dealing with different objects. But the rule is simple, each added observer must implement

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 

One more thing: It’s a good idea to create a context for observation, for example,

 //In MyViewController.m //.. static int observingViewFrameContext // In ... [self addObserver:self forKeyPath:@"view.frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:&observingViewFrameContext]; // .. don' forget to remove an observer ! too 
+2
source

Source: https://habr.com/ru/post/908338/


All Articles