Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post to NSNotificationCenter regarding bool state?

I'm trying to get the hang of using notifications. In my view controller class, I have a bool isFullScreen. When the value of this bool changes, I want to a notification to be sent to all observing classes. I'm not quite sure how to go about doing this, since a BOOL is not an object. How would I accomplish this?

like image 673
Snowman Avatar asked Mar 23 '12 14:03

Snowman


People also ask

What is the difference between nsdistributednotificationcenter and a Notification Center?

A notification center can deliver notifications only within a single program; if you want to post a notification to other processes or receive notifications from other processes, use NSDistributedNotificationCenter instead.

Why does Anan call the defaultcenter Notification Center multiple times?

An object may therefore call this method several times in order to register itself as an observer for several different notifications. Each running app has a defaultCenter notification center, and you can create new notification centers to organize communications in particular contexts.

How do I get notifications from a specific object?

Objects register with a notification center to receive notifications ( NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. When an object adds itself as an observer, it specifies which notifications it should receive.

What is the defaultcenter Notification Center?

Each running app has a defaultCenter notification center, and you can create new notification centers to organize communications in particular contexts.


1 Answers

[[NSNotificationCenter defaultCenter] postNotificationName:YourNotificationName object:[NSNumber numberWithBool:isFullScreen]]; //YourNotificationName is a string constant

KVO Example:

If you were to do it with KVO, it would be something like the below.... :

[self addObserver:self forKeyPath:@"isFullScreen" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString: @"isFullScreen"]) {
        BOOL newValue = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
    }
}

//and in dealloc
[self removeObserver:self forKeyPath:@"isFullScreen" ];
like image 61
bandejapaisa Avatar answered Sep 18 '22 16:09

bandejapaisa