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)
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)
| 归档时间: |
|
| 查看次数: |
62938 次 |
| 最近记录: |