Objective-c TableView 刷新 dispatch_sync 错误

Objective-c TableView Refresh With dispatch_sync error

您好,我正在处理简单的 tableview json 解析代码。但我想在每次添加 dispatch_sync 代码时在后台重新加载 tableview,但不在下面运行我的代码。

NSArray * jsonArray;
NSMutableArray * array1;


- (void)viewDidLoad {
    [super viewDidLoad];


   NSURL * url = [NSURL URLWithString:@"http://bla.com/test2.json"];

    NSURLRequest * urlReq = [NSURLRequest requestWithURL:url];

    NSError * error;

    NSData * data = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:nil error:&error];

    NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    NSLog(@"%@",jsonDict);

    jsonArray = [jsonDict objectForKey:@"worldpopulation"];

    NSLog(@"%@",jsonArray);

    array1 =[[NSMutableArray alloc]init];

}

- (void)main
{

    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return jsonArray.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid=@"CustomCell";
    CustomTableViewCell *cell=(CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid];;


    if(cell==nil)
    {
        cell=[[CustomTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];

    }



    for ( NSDictionary * dict in jsonArray) {

        NSString * country = [dict objectForKey:@"country"];

        [array1 addObject:country];

    }

    cell.nameLabel.text= [array1 objectAtIndex:indexPath.row];



    return cell;
}

Main.m

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

我只添加了需要的代码。我需要修理它。 感谢您的帮助!

首先,在主线程上执行同步网络操作不是一个好主意 - 它会使您的应用程序 UI 'freeze' 直到操作完成,这在缓慢(或没有)的情况下) 网络可能会很长时间。

其次,您应该将加载代码移动到您从 viewDidLoad 调用的它自己的函数中 - 这样,如果您想重新加载数据,您可以轻松地再次调用它。

第三,您的 cellForRowAtIndexPath 正在为每个单元格迭代整个 jsonArray,但没有任何意义。

最后,NSURLConnection 在 iOS 9 中被弃用,因此如果您的目标是 iOS7 及更高版本(如果您想 运行 on iOS before iOS 7 然后你需要继续使用 NSURLConnection)

我建议如下:

@interface MyViewController () <UITableViewDelegate,UITableViewDataSource>

@property (strong,nonatomic) NSArray *jsonArray;

@end

@implementation MyViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    self.jsonArray=[NSArray new];
    [self loadJSON];
}

-(void)loadJSON {

    NSURL * url = [NSURL URLWithString:@"http://bla.com/test2.json"];
    NSURLSession *session=[NSURLSession sharedSession];

   [session dataTaskWithRequest:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error!=nil) {
            NSLog(@"Something went wrong:%@",error);
        } else {
            NSError *jsonError;
            NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonEerror];
            if (jsonError != nil) {
                NSLog(@"JSON isn't right:%@",jsonError);
            } else {
                self.jsonArray = jsonDict[@"worldpopulation"];
                dispatch_async(dispatch_get_main_queue(),^{
                    [self.tableview reloadData];
                }); 
            }
    }];

}


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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid=@"CustomCell";
    CustomTableViewCell *cell=(CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];;

    NSDictionary *entryDict=self.jsonArray[indexPath.row];
    NSString *countryName=entryDict[@"country"];

    cell.nameLabel.text= countryName;
    return cell;
}