解析稍微复杂一点的数据

碰到如上图所示的数据需要我们解析,用"name"的值作为分区头标题,用上图所圈起来的字典作为一个model,我们可以用两种方式解析:

第一种方式:就是使用一个数组和一个字典,数组用来存储"name"里的值,作为key;字典用来存储所有数据;

第二种方式:就是使用两个数组,其中一个数组用来存储"name"的值,另一个数组存储所有数据;

闲言修叙:直接上代码

第一种方式:

#import "RootTableViewController.h"
#import "YHCell.h"

@interface RootTableViewController ()

@property (nonatomic, strong) NSMutableArray *allKeysArray;
@property (nonatomic, strong) NSMutableDictionary *allDataDict;

@end

@implementation RootTableViewController

// 懒加载
- (NSMutableDictionary *)allDataDict {
    
    if (!_allDataDict) {
        _allDataDict = [NSMutableDictionary dictionary];
    }
    return _allDataDict;
}

- (NSMutableArray *)allKeysArray {
    
    if (!_allKeysArray) {
        _allKeysArray = [NSMutableArray array];
    }
    return _allKeysArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"旅游";
    self.tableView.showsVerticalScrollIndicator = NO;
    
    
    // 数据处理
    [self loadWebData];
    
    
    // 注册cell
    [self.tableView registerClass:[YHCell class] forCellReuseIdentifier:@"cell"];
    
}


// 数据处理
- (void)loadWebData {
    NSURL *url = [NSURL URLWithString:@"http://api.yhouse.com/m/city/dynmiclist"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSDictionary *dict1 = dict[@"data"];
            NSArray *array = dict1[@"allCity"];
            
            for (int i = 0; i < array.count; i++) {
                NSDictionary *dict2 = array[i];
                
                NSMutableArray *dataArray = [NSMutableArray array];
                for (NSString *key in dict2) {
                    
                    if ([key isEqualToString:@"name"]) {
                        NSString *value = dict2[key];
                        [self.allKeysArray addObject:value];
                    }
                    
                    if ([key isEqualToString:@"tabs"]) {
                        for (NSDictionary *dict3 in dict2[key]) {
                            Model *model = [[Model alloc] init];
                            [model setValuesForKeysWithDictionary:dict3];                        
                            [dataArray addObject:model];
                        }
                    }
                }
                [self.allDataDict setObject:dataArray forKey:[self.allKeysArray lastObject]];
            }
            [self.tableView reloadData];
        }
    }];
    
    [task resume];
}

// 设置分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataHandle.allKeysArray.count;
}

// 设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *key = self.dataHandle.allKeysArray[section];
    NSInteger index = [self.dataHandle.allDataDict[key] count];
    return index;
}


// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YHCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    Model *model = [[Model alloc] init];
    NSString *key = self.dataHandle.allKeysArray[indexPath.section];
    model = self.dataHandle.allDataDict[key][indexPath.row];
    
    // 给cell赋值
    [cell bindModel:model];

    
    return cell;
}


// 设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}


// 设置头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return self.dataHandle.allKeysArray[section];
}

@end

第一种方式中间的解析数据也可以全用foin循环来解析,也就是还可以简化一点代码:

- (void)loadWebData {
    NSURL *url = [NSURL URLWithString:@"http://api.yhouse.com/m/city/dynmiclist"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSDictionary *dict1 = dict[@"data"];
            NSArray *array = dict1[@"allCity"];
            
            for (NSDictionary *dict2 in array) {
                [self.allKeysArray addObject:dict2[@"name"]];
                
                NSMutableArray *array1 = [NSMutableArray array];
                for (NSDictionary *dict3 in dict2[@"tabs"]) {
                    Model *model = [[Model alloc] init];
                    [model setValuesForKeysWithDictionary:dict3];
                    [array1 addObject:model];
                }
                [self.allDataDict setObject:array1 forKey:[self.allKeysArray lastObject]];
            }
        }
        [self.tableView reloadData];
    }];
    
    [task resume];
}

第二种方法:

#import "RootTableViewController.h"
#import "YHCell.h"

@interface RootTableViewController ()

@property (nonatomic, strong) NSMutableArray *allKeysArray;
@property (nonatomic ,strong) NSMutableArray *allDataArray;

@end

@implementation RootTableViewController

// 懒加载
- (NSMutableArray *)allKeysArray {
    
    if (!_allKeysArray) {
        _allKeysArray = [NSMutableArray array];
    }
    return _allKeysArray;
}

- (NSMutableArray *)allDataArray {
    
    if (!_allDataArray) {
        _allDataArray = [NSMutableArray array];
    }
    return _allDataArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"旅游";
    self.tableView.showsVerticalScrollIndicator = NO;
    
    
    // 数据处理
    [self loadData];
    
    
    // 注册cell
    [self.tableView registerClass:[YHCell class] forCellReuseIdentifier:@"cell"];
    
}


// 数据处理
- (void)loadData {
    
    NSURL *url = [NSURL URLWithString:@"http://api.yhouse.com/m/city/dynmiclist"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSDictionary *dict1 = dict[@"data"];
        NSArray *array = dict1[@"allCity"];
        
        for (NSDictionary *dict2 in array) {
            
            NSMutableArray *array1 =[NSMutableArray array];
    
            [self.allKeysArray addObject:dict2[@"name"]];
            
            for (NSDictionary *dict3 in dict2[@"tabs"]) {
                Model *model = [[Model alloc] init];
                [model setValuesForKeysWithDictionary:dict3];
                [array1 addObject:model];
            }
            
            [self.allDataArray addObject:array1];
        }
        [self.tableView reloadData];
        
    }];
    
    [task resume];

}


// 分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.allKeysArray.count;
}

// 每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.allDataArray[section] count];
}


// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YHCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    Model *model = [[Model alloc] init];
    NSArray *array = self.allDataArray[indexPath.section];
    model = array[indexPath.row];
    
    // 给cell赋值
    [cell bindModel:model];
    
    
    return cell;
}


// 设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}


// 设置头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return self.allKeysArray[section];
}

@end
原文地址:https://www.cnblogs.com/dongbaoyue/p/5525257.html