2012-02-26 31 views
0

正如我在這裏告訴我,我使用NSNotificationCenterNSNotificationCenter不工作?

上init方法類A(觀察者)我有:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSensorsData:) name:@"HotSpotTouched" object:nil]; 

CLASSB我有:

//FILL NSDICTIONARY WITH DATA 
    [dict setObject:@"SPOT1" forKey:[array objectAtIndex:0]]; 
    [dict setObject:@"SPOT2" forKey:[array objectAtIndex:1]]; 
    [dict setObject:@"SPOT3" forKey:[array objectAtIndex:2]]; 
    [dict setObject:@"SPOT4" forKey:[array objectAtIndex:3]]; 
    [dict setObject:@"SPOT5" forKey:[array objectAtIndex:4]]; 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"HotSpotTouched" object:dict]; 

在類函數A getSensorsData不被稱爲。

這裏有什麼錯?

謝謝!

+0

你對'getSensorsData'的聲明是什麼樣的?它在你的'.h'接口文件中嗎? – 2012-02-26 16:16:13

+0

@MichaelDautermann: - (void)getSensorsData:(NSNotification *)SPOTS – Curnelious 2012-02-26 16:18:47

+1

該聲明看起來可能是錯誤的。編輯您的問題以顯示您的聲明以及您如何訪問'getSensorsData'內的'NSDictionary'。你是否設置了一個斷點,並且在通知觸發時沒有觸發? classB發生在不同的線程上嗎? – 2012-02-26 16:22:54

回答

-1

問題就迎刃而解了:

如果將null參數傳遞,觀察者沒有得到來電!

我的NSDictionary參數是空的(因爲我仍然不知道的原因),所以這個調用沒有被解僱。

3

您在發送通知時傳遞 dict作爲 notificationSender,當您添加觀察者時傳遞 nil。這樣您的通知就會被過濾掉,因爲發件人不匹配。

更新:
正如所指出joerick中的註釋添加觀察者將禁用發件人篩選時通過零。所以這不是問題。

我剛剛創建了一個小樣本項目,併爲我發送了通知。

@Rant:如果你想傳遞任意數據以及你的通知,你應該使用userInfo字典(正如Cyrille在評論中指出的那樣)。

+0

是的,那也是我的想法。 – 2012-02-26 16:26:26

+2

您想要將'dict'作爲'userData'發佈,而不是'NSNotification'的'object'。 – Cyrille 2012-02-26 16:27:38

+1

將'nil'傳遞給'addObserver:...'意味着所有通知都被觀察到,而不管發件人。 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference。html – joerick 2012-02-26 16:29:19

3

對通知中心的呼叫看起來是正確的。我懷疑問題是由於對象A的liffe循環造成的。您說您正在註冊init方法中的通知。你有沒有正確分配self

-(id)init 
{ 
    //self does not have a meaningful value prior to the call to [super init] 
    self = [super init]; 
    if (self != nil) 
    { 
     //ensure addObserver is called in the if code block 
    } 
    return self; 
} 

此外,這是很好的做法,因爲他們對減輕錯別字使用常量通知的名字。見Constants in Objective C

+0

感謝您的回答,我這樣做: - (id)init {if((self = [super init]))....那樣可以嗎? – Curnelious 2012-02-27 07:55:12

+0

我也嘗試完全按照你的說法,它打印if語句下的nslog。 – Curnelious 2012-02-27 08:01:59

相關問題