-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:对象:用户信息:

基本上观察者是如何获得该用户信息的?

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

4

2 回答 2

1

基本上观察者是如何获得该用户信息的?

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

于 2012-06-02T17:47:10.813 回答
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];
    }
}
于 2012-06-02T18:13:40.597 回答