2010-11-30 117 views
69

有人请告诉我如何在NSNotifcationCenter上使用对象属性。我想能够使用它来传递一个整数值给我的选择器方法。如何使用NSNotificationcenter的对象属性

这就是我在UI视图中设置通知侦听器的方式。看到我想要传递一个整数值,我不知道要用什么来替换零。

[[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#> 
} 

回答

102

object参数表示该通知的发送方,通常是self

如果您想传递额外的信息,则需要使用方法postNotificationName:object:userInfo:,该方法接受任意值的字典(您可以自由定义)。内容需要是实际的NSObject实例,而不是像整数这样的整数类型,所以您需要用NSNumber对象包装整数值。

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

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

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]; 
} 
+0

“对象属性不适用于此。”为什么它不合适?无论如何,如果我尝试使用对象属性传递(例如)一个NSString *。会发生什么? – Selvin 2013-04-14 10:57:52

+1

@Selvin用于发送发布通知的对象(如果要使用它,则将其设置为“self”)。如果你把其他东西放在那里会发生什么?我不知道,但如果我不得不猜测,它可能会弄乱封面上发生的事情,比如通知中心跟踪需要发布的内容。为什么存在一个用于传递物体的实际系统时存在风险? – 2013-04-15 19:19:30