73

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

这就是我在 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#>
}
4

2 回答 2

106

参数代表通知的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];
于 2010-11-30T10:51:40.640 回答
83

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];
}
于 2010-11-30T10:48:23.410 回答