如何使用NSNotificationcenter的object属性

dub*_*eat 72 iphone cocoa objective-c nsnotificationcenter

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

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

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


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

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

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

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

gav*_*inb 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];
Run Code Online (Sandbox Code Playgroud)

  • (哦,我的解决方案和Matthew一样,我只是设法点击提交更快一点!) (3认同)

Mat*_*ick 82

object物业不适合.相反,您想要使用userinfo参数:

+ (id)notificationWithName:(NSString *)aName 
                    object:(id)anObject 
                  userInfo:(NSDictionary *)userInfo
Run Code Online (Sandbox Code Playgroud)

userInfo 正如您所看到的,是一个专门用于发送信息和通知的NSDictionary.

你的dispatchFunction方法将是这样的:

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

你的receiveEvent方法是这样的:

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

  • "NSNotification对象(称为通知)包含名称,对象和可选字典.名称是标识通知的标记.对象是通知的海报要发送给观察者的任何对象通知 - 通常是发布通知本身的对象.字典可能包含有关该事件的其他信息." 听起来像在`object:`中添加除`self`和`nil`之外的东西是完全没问题的. (3认同)