我想用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?");
}
永遠不會被調用。
爲什麼你不只是調用圖像變化的功能,當您更改背景圖片?我不確定你需要通知中心。 – Dustin 2012-07-17 18:21:25
您是否正在更新跨類的圖像視圖?如果沒有,那麼我不會使用觀察者模式。觀察者模式用於發送全局更新,如果這些更改全部在同一個類中進行,則不應使用該模式。 如果處理不當,可能會遇到很多觀察者遇到的問題。如嘗試添加現有的或刪除不存在的。 我建議,如果這是這一切被在同一類處理,只是用邏輯來確定何時更新相應圖像視圖。 – random 2012-07-17 18:24:56
那麼上面的代碼會如何導致問題呢? – JohnMerlino 2012-07-17 18:33:52