2013-10-25 18 views
0

我正在使用UITableView。如果没有网络连接,那么会在viewDidload中引发异常。我viewDidLoad中的功能是:不能在异常情况下显示UIAlert

@try { 
       NSLog(@"Request URL = %@",URLString); 

       NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL 
                    URLWithString:URLString]]; 
       NSData *response = [NSURLConnection sendSynchronousRequest:request 
                returningResponse:nil error:nil]; 

       NSError *jsonParsingError = nil; 
       NSDictionary *tableData = [NSJSONSerialization JSONObjectWithData:response 
                     options:0 
                     error:&jsonParsingError]; 
       // Grab whole data with data field in JSON 
       // responseArray = [tableData objectForKey:@"data"]; 


       responseArray = [[NSMutableArray alloc]initWithArray:[tableData objectForKey:@"data"]]; 
       for(int i = 0; i < responseArray.count; i++) 
       { 
        NSArray * tempArray = responseArray[i]; 
        responseArray[i] = [tempArray mutableCopy]; 
       } 


       UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
       [btn setFrame:CGRectMake(280.0, 0.0, 40.0, 40.0)]; 
       [btn setImage:[UIImage imageNamed:@"sort_icon.png"] forState:UIControlStateNormal]; 
       [btn addTarget:self action:@selector(showActionSheet) forControlEvents:UIControlEventTouchUpInside]; 
       UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithCustomView:btn]; 
       self.navigationItem.rightBarButtonItem = barbutton; 

     } 
     @catch (NSException *exception) 
     { 
      exceptionOccured = YES; 
      NSLog(@"Exception Ocurred"); 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error in connectivity" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
      [alert show]; 
     } 

在的cellForRowAtIndexPath我这样做:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    @try { 

    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init]; 
    tempDict = [responseArray objectAtIndex:indexPath.row]; 

    return cell; 

    } 
    @catch (NSException *exception) 
    { 
     NSLog(@"Error in CEll Create"); 
     NSLog(@"Draw Alert"); 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error in connectivity" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alert show]; 
    } 
} 

和AlertViewDelegate功能我做

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 

    [self.navigationController popViewControllerAnimated:YES]; 
} 

现在的问题是,它没有显示警报每当出现异常并重新抛出异常并显示错误时

Thread 1: EXC_BAD_ACCESS(code=2, address=0x2) 

任何帮助将不胜感激...

+2

您应该重写代码以避免引发异常。它们不适用于网络连接不可用等正常情况。 –

+0

仅仅因为你发现异常并不意味着它会自动消失。您只是有机会清理这种情况并将您的数据重置为“稳定”状态。在这里,您只是显示警报,并且不采取进一步的行动来纠正问题,因此异常情况仍然会下降并上升。 – Cyrille

+0

@Cyrille那么,我应该怎么做才能阻止它创造更多的细胞? – Atul

回答

1

你应该避免在你的代码中抛出异常。

首先,您可以使用Reachability Class来确定是否有活动的Internet连接可用。

我会明确推荐使用NSURLConnectionDelegate协议来进行URL连接。所以你可以使用更好的异步编程风格。

+0

只有在出现错误后,才能使用可达性加载某些内容以找出相应错误消息的原因或自动刷新行为。如果您想知道您是否可以加载某些内容,请尝试加载并处理该错误。 (可达性不能保证在线时失败或脱机时失败,因此在你加载之前询问它是没有意义的。) –

+0

没有保证,没错。但实际上,可达性非常快速和准确。你可以依靠它没有问题。对于几乎所有应用程序来说,可达性都足够好。 –

+0

不幸的是,我完全不同意你的评价,你可以毫不犹豫地依靠它。例如,如果您的服务器正在返回HTTP 500错误,则Reachability会报告您确定,但在加载数据时您将收到错误消息。你必须处理错误,而不是试图通过可达性来避免它们。同样,Reachability很容易报告“无连接”,但URL加载可以正常工作;例如,如果内容已经在本地缓存。 –

0

问题在别的地方。当调用- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath时,意味着系统需要重新加载tableView。因此,您不应该检查该函数内的数据。当你输入这个函数时,你应该确保你的数据是正确的。

你必须做的是首先检查在一个特定的功能您的数据:

 -(void)CheckData(NSArray *responseArray) { 
      @try { 
       //Retrieve your data & check if its valid 
       self.dataArray = responseArray; 
       [self.tableView reloadData]; 
      } 
      @catch (NSException *exception) 
      { 
       NSLog(@"Error in check Data"); 
       NSLog(@"Draw Alert"); 
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error  in connectivity" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       [alert show]; 
      } 

然后,实现您的数据源代表:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
      return [self.dataArray count]; 
     } 

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if(cell == nil){ 
      cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; 
     } 

     //TODO: Init your cell using your self.dataArray content 

     return cell; 
    } 
0

我会推荐进口这种SystemConfiguration框架和使用一样。这将检查网络连接是否可用。以下是简单代码: -

#import <SystemConfiguration/SystemConfiguration.h> 
-(void)yourMethod 
{  
    SCNetworkConnectionFlags flags = 0; 
      if (yourhostname && [yourhostname length] > 0) 
      { 
       flags = 0; 
       BOOL found = NO; 
       SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [yourhostname UTF8String]); 
       if (reachabilityRef) 
       { 
        found = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) 
        && (flags & kSCNetworkFlagsReachable) 
        && !(flags & kSCNetworkFlagsConnectionRequired); 
        CFRelease(reachabilityRef); 
        reachabilityRef = NULL; 
       } 
       if (found) 
       {  
        NSLog(@"Connection available");   
        } 
        else 
       { 
        NSLog(@"Connection not available");   
        } 
} 
+0

@ hussain Shabbir:什么是pingHost在这里? – Atul

+0

对不起,这是错字错误,请检查我已修改 –

+0

@ hussain Shabbir:这将在模拟器上工作?因为我每次都收到Connection不可用? – Atul

相关问题