有人可以告诉我如何使用 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/