2012-07-17 93 views
0

目標:iphone - 不通知被解僱

我想用Observer模式,這樣,當一個接收的UIImageView不同的背景圖像,然後2周的UIImageViews將偵聽的變化,然後改變自己。

策略:

根據我瞭解的Objective-C的觀察者模式,我決定實施nsnotificationcenter。

代碼:

自我指RemoteViewManagerController,updateButtons是當ImageSwap事件被觸發,將被調用的方法和對象指的是「主」的UIImageView,也就是改變了當的UIImageView會導致其他uiimageviews的變化。

- (void)registerButtonObserver:(UIView *)currentView 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateButtons:) name:@"ImageSwap" object:[self.view viewWithTag:1]]; 
} 

setDefaultButtons被調用時,我們通過基於標籤的按鈕和目標按鈕迭代。 「main」uiviewimage的標籤爲1.因此,我們調用setImageChange來更改該按鈕的背景圖像,結果,我想觸發ImageSwap事件,更改其他兩個uiimageview按鈕,然後通過這些按鈕按鈕是userinfo字典的一部分。這個想法是當updateButton被調用時,我可以引用userinfo字典中的那些按鈕。

- (void)setDefaultButtons:(UIView *)currentView 
{ 
    for(UIView *view in currentView.subviews) { 
     if([view isKindOfClass:[UIButton class]]) { 
      if(view.tag == 1){     
       [self setImageChange:@"fence" forButton:view]; 

       NSArray *keys = [NSArray arrayWithObjects:@"subview1", @"subview2", nil]; 
       NSArray *objects = [NSArray arrayWithObjects:[self.view viewWithTag:4], [self.view viewWithTag:5], nil]; 
       NSDictionary *items = [NSDictionary dictionaryWithObjects:objects 
                     forKeys:keys]; 
       NSLog(@"But we sure to get here right"); 
       [[NSNotificationCenter defaultCenter]postNotificationName:@"ImageSwap" object:view userInfo:items];     
      } 
      else if(view.tag == 2){ 
       [self setImageChange:@"siren" forButton:view]; 
      } 
      else if(view.tag == 3){ 
       [self setImageChange:@"auxiliary" forButton:view]; 
      } 
     } 
    } 
} 

注意,我知道,我們得到的postNotificationName線,因爲這條線不火的NSLog(@「但是,我們一定要拿到這裏權」);

我沒有得到任何錯誤。但是,這條線在RemoteViewManagerController.m:

- (void)updateButtons:(NSNotification*)notification 
{ 
    NSLog(@"Do we get here?"); 
} 

永遠不會被調用。

+0

爲什麼你不只是調用圖像變化的功能,當您更改背景圖片?我不確定你需要通知中心。 – Dustin 2012-07-17 18:21:25

+0

您是否正在更新跨類的圖像視圖?如果沒有,那麼我不會使用觀察者模式。觀察者模式用於發送全局更新,如果這些更改全部在同一個類中進行,則不應使用該模式。 如果處理不當,可能會遇到很多觀察者遇到的問題。如嘗試添加現有的或刪除不存在的。 我建議,如果這是這一切被在同一類處理,只是用邏輯來確定何時更新相應圖像視圖。 – random 2012-07-17 18:24:56

+0

那麼上面的代碼會如何導致問題呢? – JohnMerlino 2012-07-17 18:33:52

回答

1

我相信,當兩個子視圖具有相同的標籤,-viewWithTag:剛剛返回它找到的第一個。所以如果碰巧有tag = 1的兩個視圖,你很可能會觀察到錯誤的視圖。嘗試-addObserver...呼叫改變object參數你nil,這將表明要觀察所有對象的通知。

+0

我只是把它當做一個測試 - 它會是一個簡單的方法來確定你是否觀察錯誤的對象。 – Caleb 2012-07-17 18:35:08

+0

所以你說的那個對象PARAM表明我要遵守通知時設定爲零的所有對象,但我認爲的addObserver參數是什麼決定誰將會觀察,在這種情況下它被設置爲self。 – JohnMerlino 2012-07-17 18:42:39

+0

做觀察的對象是'self'。 「自我」觀察的對象是[自我。查看viewWithTag:1]'。我上面說的是''[self.view viewWithTag:1]'可能不是您認爲它的視圖 - 如果視圖層次結構中的某個其他視圖也具有tag = 1,那麼您可能正在觀察該視圖而不是你想到的那個。在任何*對象發佈名爲「ImageSwap」的通知時,在'-addObserver:...'調用中將'nil'替換爲'[self.view viewWithTag:1]'將調用'updateButton:'方法。 – Caleb 2012-07-17 18:48:14