2010-11-30 118 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