0

我正在使用 UITableView。如果没有网络连接,viewDidload 会抛出异常。我的 viewDidLoad 函数是:

 @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)

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

4

3 回答 3

1

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

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

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

于 2013-10-25T13:22:32.050 回答
0

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

您要做的是首先在特定功能中检查您的数据:

     -(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;
    } 
于 2013-10-25T13:44:38.730 回答
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");         
                  }
}
于 2013-10-25T13:49:41.523 回答