2012-05-10 34 views
0

從處理Web服務連接的對象中,當網絡發生故障時,我將警報傳遞給使用Web服務對象的視圖控制器。UIAlertView didmissWithClickedButtonIndex並不關閉警報

WebServiceObject:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Connection failed! You must be connected to a Wifi source to download data. Please reconnect to a Wifi source and try again later."] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil]; 
    NSDictionary *alertDict = [NSDictionary dictionaryWithObjectsAndKeys:alert, @"AlertView", nil]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:DisplayAlertNotification object:self userInfo:alertDict]; 

的ViewController:

- (void)displayAlert:(NSNotification *)notification { 
    NSDictionary *dict = [notification userInfo]; 
    if ([[dict objectForKey:@"AlertView"] isKindOfClass:[UIAlertView class]]) { 
     UIAlertView *alert = [dict objectForKey:@"AlertView"]; 
       NSNumber *theTag = [dict objectForKey:@"AlertTag"]; 
    NSLog(@"%i", [theTag integerValue]); 
    alert.tag = [[dict objectForKey:@"AlertTag"] integerValue]; 
     [alert show]; 
    } 
} 


- (void)removeAlert:(NSNotification *)notification { 
    NSDictionary *dict = [notification userInfo]; 
    if ([[dict objectForKey:@"AlertTag"] isKindOfClass:[NSNumber class]]) { 
     NSNumber *theTag = [dict objectForKey:@"AlertTag"]; 
     UIAlertView *alert = (UIAlertView *)[self.view viewWithTag:[theTag integerValue]]; 
     // Not sure why but my alert is nil at this point 
     [alert dismissWithClickedButtonIndex:0 animated:YES]; 
    } 
} 

我也用removeAlert方法以同樣的方式以編程方式刪除警報。這樣做的目標是,如果網絡發生故障,但用戶沒有點擊確定,然後網絡恢復運行,我將關閉網絡失敗警報,並顯示網絡恢復警報。它的工作原理除了解除警報並顯示網絡恢復後,一旦用戶在恢復網絡上單擊確定,原始網絡故障僅恢復一次。如果用戶在出現「網絡失敗」時單擊「確定」,它將不會恢復。

我是否以正確的方式解除警報?謝謝。

編輯:我可以通過在WebServiceObject中保存一個引用並以這種方式解除引用來實現它。

回答

1

你設置警戒到零,所以它什麼都不做

alert = nil; 

[alert dismissWithClickedButtonIndex:0 animated:YES]; 
+0

你是在零部分正確。我後來補充說,因爲警報仍在顯示,我在錯誤的地方添加了該警報。即使沒有它,它仍然不會使警報消失。 – Crystal

+0

所以問題可能是你沒有得到正確的「警報」,「viewWithTag」可能會返回零,只是檢查它 – adali

+0

爲什麼你不只是通過[dict objectForKey:@「AlertView」]在removeAlert ?也許你應該把「alert」設置爲一個成員變量 – adali