Send and Receive Messages Through Nsnotificationcenter in Objective-C

Send and receive messages through NSNotificationCenter in Objective-C?

@implementation TestClass

- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}

- (id) init
{
self = [super init];
if (!self) return nil;

// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];

return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.

if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}

@end

... somewhere else in another class ...

- (void) someMethod
{

// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];

}

How to send & receive data using NSNotificationCenter in iOS (XCode6.4)

As others have noted, NSNotificationCenter doesn't work like a post office. It only delivers notifications if someone actually listens to them at the moment they arrived. This is the reason your eventListenerDidReceiveNotification method is not being called: you add an observer in viewWillAppear, which is called after the segue (I assume that you're using segues because of the performSegueWithIdentifier method in your code) is finished, so it's definitely called after postNotification has been called.

So, in order to pass data via NSNotificationCenter you have to add an observer before you post a notification.
The following code is completely useless and unnecessarily overcomplicated, you shouldn't do anything like that, but since you keep insisting on using a scheme like this, here you go:

//Didn't test this code. Didn't even compile it, to be honest, but it should be enough to get the idea.

NSString * const SOUselessNotificationName = @"MyUselessNotification";

#pragma mark - FIRST VC

@interface SOFirstVC : UIViewController
@end

@implementation SOFirstVC

NSString * const SOasGoSegueIdentifer = @"asGo";

- (IBAction)btnClicked:(id)sender {
[self performSegueWithIdentifier:SOasGoSegueIdentifer sender:self];
}

-(void)postNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:SOUselessNotificationName object:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifer isEqualToString:SOasGoSegueIdentifer]) {
SOSecondVC *destinationVC = (SOSecondVC *)segue.destinationViewController;

[destinationVC registerToReceiveNotificationsFromObject:self];
[self postNotification];
}
}

@end

#pragma mark - SECOND VC

@interface SOSecondVC : UIViewController

-(void)registerToReceiveNotificationsFromObject:(id)object;

@end

@implementation SOSecondVC

-(void)registerToReceiveNotificationsFromObject:(id)object {
[[NSNotificationCenter defaultCenter] addObserver:self selector:(eventListenerDidReceiveUselessNotification:) name:SOUselessNotificationName object:object];
}

-(void)eventListenerDidReceiveUselessNotification:(NSNotification*)uselessNotification {
NSLog(@"I got a useless notfication! Yay!");
}

-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

How to post and receive an NSNotifications (Objective C) | Notifications (in Swift)?

Send a notification:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyCacheUpdatedNotification" object:self];

Receive it:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"MyCacheUpdatedNotification" object:nil];

Act on it:

- (void)cacheUpdated:(NSNotification *)notification {
[self load];
}

And dispose of it:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Send and receive messages through NSNotificationCenter in swift?

To create a notification

let thisNotification = NSNotification(name: "createdNotification", object: nil)
NSNotificationCenter.defaultCenter().postNotification(thisNotification)

To observe for notifications

NSNotificationCenter.defaultCenter().addObserver(self, selector:"onCreatedNotification", name:"createdNotification", object: nil)
func onCreatedNotification(notification: NSNotification) {
print("Notification received")
}

How to create a class to send and receive events through NSNotificationCenter in Objective-C?

Ideally an object would start observing interesting events as soon as its initialized. So it will register all interesting events with the NotificationCenter inside its initialization code. sendEvent: is basically a wrapper around the postNotification: method.

@implementation A

- (id)init {
if(self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"SomeEvent" object:nil];
}
return self;
}

- (void)sendEvent {
[[NSNotificationCenter defaultCenter] postNotificationName:@"SomeOtherEvent" object:nil];
}

// Called whenever an event named "SomeEvent" is fired, from any object.
- (void)receiveEvent:(NSNotification *)notification {
// handle event
}

@end

Same for class B.

Edit 1:

You might be over-complicating the problem. A NSNotificationCenter acts as a broker to whom all events are sent and it decides who to forward that to. It's like the Observer pattern but objects don't directly observe or notify each other, but rather through a central broker - the NSNotificationCenter in this case. With that you don't need to directly connect two classes that might be interacting with each other with an #include.

While designing your classes, don't worry about how an object would get notified or how it would notify other interested objects, only that an object needs to get notified about some events when they occur, or it needs to inform NSNotficationCenter of its events when they occur.

So in short, find out all events that an object should know about and register those events in this init() method, and unregister them in the dealloc() method.

You may find this basic tutorial helpful.

send notification from swift file and recieve in objective c file in ios

You are creating an object of ClassB AFTER posting the notification. So while the notif is posted, the ClassB object doesn't exist. Make sure ClassB's viewDidLoad: is called before you post the notification. Only then will ClassB be able to listen to the notif and get the value

How to send and receive data along with the event in Objective-C?

There are two ways - one, you can pass any one object in with a notification - look at

+ (id)notificationWithName:(NSString *)aName object:(id)anObject

The second thing is, you can also pass an optional dictionary with as many objects as you like in it, you just need to have both sides agree on the keys used to store and retrieve the objects. That call is:

+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfo

You can always pass a nil for either anObject or userInfo in either call.

An example call that sends a notification directly (you don't have to construct the notification first if you do not want to):

[[NSNotifcationCenter defaultCenter] postNotificationName:@"MyNotification" object:myObjectToSend];

There's also a variant of that call with userInfo added on, just as there is for notification construction.

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"TestNotification"])
{
NSDictionary* userInfo = notification.userInfo;
NSNumber* total = (NSNumber*)userInfo[@"total"];
NSLog (@"Successfully received test notification! %i", total.intValue);
}
}


Related Topics



Leave a reply



Submit