如何使用NSNotificationcenter的object属性

时间:2010-11-30 09:49:19

标签: iphone objective-c cocoa nsnotificationcenter

有人可以告诉我如何在NSNotifcationCenter上使用object属性。我希望能够使用它将整数值传递给我的选择器方法。

这就是我在UI视图中设置通知监听器的方法。看到我希望传递一个整数值,我不知道用什么替换nil。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];


- (void)receiveEvent:(NSNotification *)notification {
    // handle event
    NSLog(@"got event %@", notification);
}

我从另一个类发出通知。该函数传递一个名为index的变量。这是我希望通过通知以某种方式启动的值。

-(void) disptachFunction:(int) index
{
    int pass= (int)index;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:pass];
    //[[NSNotificationCenter defaultCenter] postNotificationName:<#(NSString *)aName#>   object:<#(id)anObject#>
}

2 个答案:

答案 0 :(得分:105)

object参数代表通知的发件人,通常为self

如果您希望传递额外信息,则需要使用NSNotificationCenter方法postNotificationName:object:userInfo:,该方法采用任意值的字典(您可以自由定义)。内容需要是实际的NSObject实例,而不是整数等整数类型,因此您需要使用NSNumber个对象包装整数值。

NSDictionary* dict = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
                                      object:self
                                      userInfo:dict];

答案 1 :(得分:82)

object属性不适合。相反,您想使用userinfo参数:

+ (id)notificationWithName:(NSString *)aName 
                    object:(id)anObject 
                  userInfo:(NSDictionary *)userInfo
正如您所看到的,

userInfo是一个专门用于发送信息和通知的NSDictionary。

您的dispatchFunction方法将改为:

- (void) disptachFunction:(int) index {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}

您的receiveEvent方法会是这样的:

- (void)receiveEvent:(NSNotification *)notification {
    int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}