2012-05-10 36 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