我需要使用的示例代码

时间:2012-06-02 17:37:37

标签: objective-c xcode4.3 nsnotifications

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:对象:USERINFO:

基本上观察者如何获得userInfo?

是否有一个简短的示例代码可以显示整个内容?

2 个答案:

答案 0 :(得分:1)

  

基本上观察者如何获得userInfo?

请参阅NSNotification类ref。它有一个属性userInfo,它是一个NSDictionary。

答案 1 :(得分: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];
    }
}