Search code examples
objective-cxcode4.3nsnotifications

I need sample code of using


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?


Solution

  • #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];
        }
    }