I assume the question is how to have the recipient of the notification to send a response back to the sender of the notification.
You can't just return a value from a notification. But the notification handler can call a method back in the original object in order to supply whatever data you wanted to pass back to it.
One way to do that is to supply an object
parameter of postNotificationName
that specifies who sent the notification. And then have that object
(the notificationSender
) conform to some protocol with some established API. For example, define a protocol for the method that the view controllers will call:
@protocol MyNotificationProtocol <NSObject>
- (void)didReceiveNotificationResponse:(NSString *)response;
@end
Then, the object issuing the notification would conform to this protocol:
@interface MyObject : NSObject <MyNotificationProtocol>
@end
@implementation MyObject
- (void)notify
{
NSDictionary *userInfo = ...;
// note, supply a `object` that is the `notificationSender`
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:self userInfo:userInfo];
}
- (void)didReceiveNotificationResponse:(NSString *)response
{
NSLog(@"response = %@", response);
}
@end
Then, the view controllers that receive the notification could use the object
parameter of the NSNotification
object to send the response:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification:) name:kNotificationName object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveNotification:(NSNotification *)notification
{
id<MyNotificationProtocol> sender = notification.object;
// create your response to the notification however you want
NSString *response = ...
// now send the response
if ([sender conformsToProtocol:@protocol(MyNotificationProtocol)]) {
[sender didReceiveNotificationResponse:response];
}
}
In the above example, the response is a NSString
, but you could use whatever type of parameter to didReceiveNotificationResponse
that you want, or add additional parameters (e.g. the sender
of the response).