如何使用nsnotificationcenter的对象属性
-
29-09-2019 - |
题
有人可以告诉我如何在nsnotifcationcenter上使用对象属性。我希望能够使用它将整数值传递给我的选择方法。
这就是我在UI视图中设置通知侦听器的方式。看到我希望通过一个整数值,我不确定该如何代替零。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveEvent:) name:@"myevent" object:nil];
- (void)receiveEvent:(NSNotification *)notification {
// handle event
NSLog(@"got event %@", 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
.
如果您想传递额外的信息,则需要使用 NSNotificationCenter
方法 postNotificationName:object:userInfo:
, ,它采用任意词典的值(您可以自由定义)。内容需要实际 NSObject
实例,而不是整数等整体类型,因此您需要将整数值包裹 NSNumber
对象。
NSDictionary* dict = [NSDictionary dictionaryWithObject:
[NSNumber numberWithInt:index]
forKey:@"index"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent"
object:self
userInfo:dict];
其他提示
这 object
财产不合适。相反,您想使用 userinfo
范围:
+ (id)notificationWithName:(NSString *)aName
object:(id)anObject
userInfo:(NSDictionary *)userInfo
userInfo
如您所见,是一个专门用于发送信息以及通知的Nsdictionary。
您的 dispatchFunction
方法将是这样的事情:
- (void) disptachFunction:(int) index {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:index] forKey:@"pass"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"myevent" object:nil userInfo:userInfo];
}
您的 receiveEvent
方法是这样的:
- (void)receiveEvent:(NSNotification *)notification {
int pass = [[[notification userInfo] valueForKey:@"pass"] intValue];
}
不隶属于 StackOverflow