AddObserver on yourself

Pretty simple question, but I can not find the answer. (IOS 5+ application development).

In my AppDelegate I have a property, let me call it @property (non atomic) BOOL aFlag; . I want my AppDelegate to be notified of a change in value. Here is what I tried (everything happens in AppDelegate.m ), which is the same as when I "link" two different objects to an observer:

 -(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { // Some stuff _aFlag = YES; [self addObserver:self forKeyPath:@"aFlag" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil]; // Some other stuff } -(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context { if ([keyPath isEqual:@"aFlag"]) { // Do something } else { // Do nothing } } 

But observeValueForKeyPath: not called.

Where am I mistaken? Thanks.

+4
source share
1 answer

You must implement your own setter. In this setter, you know what the fuck has changed.

It is more optimized in this way. Much better and cheaper than doing KVO on yourself.

Your solution works, technically you can KVO yourself.

But imagine if you started using NSNotificationCenter to run methods in a class from within your class? It can be done? Yes. Should it be? Probably no. You may have a scenario where this is normal, but not in a purely object-oriented solution. To do this, you need to send a message to self .

Well, that’s the same. Implement this:

 - (void)setAFlag:(BOOL)flag; 

For instance:

 - (void)setAFlag:(BOOL)flag{ BOOL valueChanged = NO; if(_aFlag != flag){ valueChanged = YES; } _aFlag = flag; if(valueChanged) [self doSomethingWithTheNewValueOfFlag]; } 
+10
source

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


All Articles