iphone - 如何使用 NSNotificationcenter 的 object 属性

标签 iphone objective-c cocoa nsnotificationcenter

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

这就是我在 UI View 中设置通知监听器的方式。看到我想要传递一个整数值,我不确定用什么替换 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#>
}

最佳答案

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];

关于iphone - 如何使用 NSNotificationcenter 的 object 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312338/

相关文章:

iphone - 如何检测删除按钮 UItableviewcell 是否被隐藏?

iphone - 如何从地址簿编辑 ABPersonSetImageData

iphone - 有人可以告诉我如何创建一个 CGPattern 来用图像描画路径吗?

objective-c - iOS7 和 GameKit 蓝牙

cocoa - 观察共享 UserDefaults Controller 值的任何更改

iphone - 如何滑动 tableviewcell 以获取部分中的特定行

objective-c - NSView 的边界与框架

objective-c - 自定义 NSMenu 项

cocoa - 如何将 Google Maps map 添加到 OS X Cocoa 应用程序

xcode - 如何为 Mac OS 编写互联网帐户插件?