-4

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNotificationCenter/postNotificationName:object:userInfo:

postNotificationName:object:userInfo:

Basically how does the observer get that userInfo?

Is there a short sample code somewhere to show the whole thing?

user4951
  • 32,206
  • 53
  • 172
  • 282

2 Answers2

1

Basically how does the observer get that userInfo?

See NSNotification class ref. It has a property userInfo, which is an NSDictionary.

Wienke
  • 3,723
  • 27
  • 40
1
#import <Foundation/Foundation.h>

#define kSomeKey @"key"
#define kNotificationName @"MyMadeUpNameNotification"
@interface Test : NSObject
@end
@implementation Test
-(void) handleNotification:(NSNotification*)notification {
    NSString *object = [notification.userInfo objectForKey:kSomeKey];
    NSLog(@"%@",object);
}
-(void) run {
    [[NSNotificationCenter defaultCenter] addObserver: self 
                                             selector: @selector(handleNotification:) 
                                                 name: kNotificationName 
                                               object: nil]; 
    NSString *anyObject = @"hello";
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:anyObject forKey:kSomeKey];
    NSNotification *notification = [NSNotification notificationWithName:kNotificationName object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}
@end


int main(int argc, char *argv[]) {
    @autoreleasepool {
        [[Test new] run];
    }
}
Jano
  • 62,815
  • 21
  • 164
  • 192
  • I think user info must be a dictionary there. That can't be a string and you're not inserting it. – user4951 Jun 04 '12 at 09:01
  • Sorry Jim, you are right. I edited and tested in CodeRunner this time. – Jano Jun 04 '12 at 10:20
  • So I see. Yes you give your data through user info. Like what I suspected. Thanks Jano. – user4951 Jun 04 '12 at 10:22
  • Note that the field `notification.object` may be used to pass the object that created the notification, or any object. If you have to pass a single object and you don't care what the source is, just use `notificationWithName:object:` instead `notificationWithName:object:userInfo:`. – Jano Jun 04 '12 at 16:02