如何使用NSNotificationcenter的object属性 [英] how to use the object property of NSNotificationcenter

查看:361
本文介绍了如何使用NSNotificationcenter的object属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何使用NSNotifcationCenter上的object属性。我想能够使用它传递一个整数值到我的选择器方法。

Could somebody please show me how to use the object property on NSNotifcationCenter. I want to be able to use it to pass an integer value to my selector method.

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

This is how I have set up the notification listener in my UI View. Seeing as I want an integer value to be passed I'm not sure what to replace nil with.

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


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

我从这样的另一个类调度通知。函数传递一个名为index的变量。这是我想以某种方式触发通知。

I dispatch the notification from another class like this. The function is passed a variable named index. It's this value that I want to somehow fire off with the notification.

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

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


推荐答案

> object 参数表示通知的发件人,通常 self

The object parameter represents the sender of the notification, which is usually self.

如果您想传递额外的信息,您需要使用 NSNotificationCenter 方法 postNotificationName:object:userInfo:获取值的任意字典(您可以自由定义)。内容需要是实际的 NSObject 实例,而不是整数类型,如整数,所以你需要包装整数值与 NSNumber objects。

If you wish to pass along extra information, you need to use the NSNotificationCenter method postNotificationName:object:userInfo:, which takes an arbitrary dictionary of values (that you are free to define). The contents needs to be actual NSObject instances, not an integral type such as an integer, so you need to wrap the integer values with NSNumber objects.

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

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

这篇关于如何使用NSNotificationcenter的object属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆