iphone开发之表格组件UITableView的使用(三)通过加载plist文件字典转模型方式展示分组数据

本文主要是介绍iphone开发之表格组件UITableView的使用(三)通过加载plist文件字典转模型方式展示分组数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、通过加载plist文件,利用在懒加载中把字典转模型实现的步骤如下:
(1)新建plist文件,编辑plist文件内容添加属性。编辑步骤如下:
在文件中新建一个NSArray用来包含所有的数据,点击大的NSArray数据的三角符号向下,新建元素字典作为NSArray的每一项内容,为第一个数组元素即字典添加属性(包括组标题,组尾描述,小的NSArray:用来描述当前组的每一行内容)。然后选中第一个字典(数组的第一项)复制粘贴…为整体的NSArray数组添加项目。
(2)新建model对象。除了添加和字典对应的属性外还要添加两个返回值类型为instancetype的初始化类方法和对象方法。
(3)编辑model对象的初始化方法
注意:在初始化方法中可以把参数字典对象的每一个属性逐个赋值给model对象的对应属性,但是当对象的属性很多即字典的键值对很多时就会变得非常麻烦。
解决方法:在初始化方法中利用对象的如下方法:
[self  setValueForKeysWithDictionary:dict]; 就会把字典中每一个键对应的值一一赋值给model对象中和字典键名相同的属性变量。
具体代码示例如下:
-(instancetype)initWithDict: (NSDictionary *)dict
{
      if(self = [super init])
   {
         //self.title = dict[@“title”];
        // self.desc = dict[@“desc”];
        // self.cars =dict[@“cars”];
      [self  setValuesForKeyWithDictionary:  dict]; // KVC 中的方法
   }
return  self;
}
-(instancetype)groupWithDict: (NSDictionary *)dict
{
    return [[self alloc] initWithDict: dict];
}
(4)在控制器的.h文件中添加一个数组属性  
@property(nonatomic,strong)NSArray  *groups;
(5)重写数组属性的get方法,并在方法内实现懒加载。具体步骤如下:
1>找到plist文件的路径,(用[[NSBundle mainBundle] pathForResource:…] 方法实现)。
2>加载plist文件。利用数组的arrayWithContentOfFile方法。
3>把字典转成模型。新建一个空的可变数组。用来存放model对象。
4>  遍历字典数组中的每一个字典,把字典转换成模型,把模型放到存放model对象的数组中。
5>把存放model的可变数组赋值给数组属性变量。
6>返回下划线数组变量属性。  
(切记:不可在重写get方法中返回self.数组属性,否则自己调用自己造成死循环)。 具体代码如下:
-(NSArray *)groups
{
if(_group == nil){
   // 懒加载数据
          //找到plist文件的路径
       NSString *path = [[NSBundle mainBundle] pathFOrResource:@“XXX.plist”ofType:nil];
  // 加载plist文件
     NSArray *arrayDict = [NSArray arrayWithContentsOfFile:path];
           //把字典转为模型
      NSMutableArray  *arrayModel = [NSMutableArray  array];
         // 遍历字典数组中的每一个字典,把每个字典转成模型,并把模型放到arrayModel数组中
      for(NSDictionary * dict  in  arrayDict)
         {
              // 创建模型对象
              CZGroup  *model = [CZGroup  groupWithDict: dict];
              [arrayModel  addObject: model];
          }
        _groups = arrayModel;
   }
    return _groups;
}
(6)拖拽或新建一个UITableView属性变量,并在viewDidLoad方法中对其属性进行设置。让当前控制器遵守UITableViewDataSource协议,即让当前控制器作为UITableView组件的数据源对象。
(7)设置UITableView组件的dataSource属性为当前控制器,即
self.tableView.dataSource = self; 或者拖线实现。
(8)添加并实现数据源协议中的几个方法。如下所示:
-(NSTnteger)numberOfSectionsInTableView:(UITableView *) tableView
{  // 此方法用于告诉UITableView组件分为几个组
    return self.groups.count; // 数组元素的个数即是组数
 }
-(NSInteger) tableVIew: (UITableVIew *)tableView numberOfRowsInSection:(NSInteger) section; 
{  // 此方法用于用于返回每一组的行数
    // 根据组索引(section)获取组对象
   CGGroup  *group = self.groups[section];
   return  group.cars.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ // 此方法用于返回每一组每一行的内容(单元格UITableViewCell) 具体步骤如下:
    //  1、获取模型数据
        //获取组模型
         CZGroup  *group = self.groups[indexPath.section];
         //获取对应的汽车品牌
        NSString  *brand = group.cars[indexPath.row];
    //   2、创建单元格UITableViewCell
     UITableViewCell *cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault  reuseIndentifier:nil];
    //   3、把模型中的数据设置给单元格中的子控件
          //把汽车品牌设置给单元格中的Label
          cell.textLabel.text = brand;
    //   4、返回单元格UITableViewCell
         return cell;
}
-(NSString *)tableView:(UITableView *)tableView  titleForHeaderInSection:(NSInteger) section;
{  // 此方法用于给每一组添加组标题
     CZGroup *group = self.groups[section];
    return  group.title;
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
{  // 返回组尾描述
   CZGroup *group = self.groups[section];
    return  group.desc;
}
(9)非常重要的一条:在创建UITableView时千万不能忘记设置风格。因为默认下是plain不分组的。要进行属性设置为group。如下所示:

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];

代码验证示例如下:

新建一个具有simple View的工程

首先在Supporting files文件夹下新建一个plist文件,编辑内容如下:


用记事本打开,其实是一个xml文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array><dict><key>cars</key><array><string>奥迪</string><string>宝马</string><string>奔驰</string><string>保时捷</string><string>大众</string></array><key>title</key><string>德系品牌</string><key>desc</key><string>高端大方上档次,世界一流品牌</string></dict><dict><key>cars</key><array><string>本田</string><string>丰田</string><string>铃木</string><string>雷克萨斯</string><string>马自达</string><string>日产</string><string>三菱</string><string>现代</string></array><key>title</key><string>日韩品牌</string><key>desc</key><string>牛逼哄哄,哎哟,好像不错</string></dict><dict><key>cars</key><array><string>别克</string><string>福特</string><string>Jeep</string><string>凯迪拉克</string><string>林肯</string><string>雪佛兰</string></array><key>title</key><string>美系品牌</string><key>desc</key><string>老牌汽车,复古风</string></dict><dict><key>cars</key><array><string>标致</string><string>雪铁龙</string><string>宾利</string><string>捷豹</string><string>路虎</string><string>劳斯莱斯</string><string>法拉利</string><string>兰博基尼</string><string>玛莎拉蒂</string></array><key>title</key><string>欧系其他</string><key>desc</key><string>优雅高贵,你值得拥有</string></dict><dict><key>cars</key><array><string>比亚迪</string><string>奔腾</string><string>北京汽车</string><string>长城</string><string>东南</string><string>东风</string></array><key>title</key><string>自主品牌</string><key>desc</key><string>Made In China,质量你懂的</string></dict>
</array>
</plist>

   在Supporting下根据plist文件内的字典属性新建model类型的类 Group

编辑Group.h如下:

//
//  group.h
//  通过加载plist文件来展示分组数据
//
//  Created by apple on 15/8/31.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//#import <Foundation/Foundation.h>@interface Group : NSObject
@property (nonatomic, strong)  NSArray  *cars;
@property (nonatomic, strong)  NSString *title;
@property (nonatomic, strong)  NSString *desc;-(instancetype) initWithDict:(NSDictionary *)dict;
+(instancetype) groupWithDict:(NSDictionary *)dict;
@end
编辑Group.m如下:

//
//  group.m
//  通过加载plist文件来展示分组数据
//
//  Created by apple on 15/8/31.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//#import "group.h"@implementation Group
-(instancetype) initWithDict:(NSDictionary *)dict
{if (self = [super init]){// 第一种方式
//        self.desc = dict[@"desc"];
//        self.title  = dict[@"title"];
//        self.cars = dict[@"cars"];// 第二种方式KVC[self setValuesForKeysWithDictionary:dict];}return self;
}
+(instancetype) groupWithDict:(NSDictionary *)dict
{return [[self alloc] initWithDict:dict];
}
@end
编辑控制器类的.h文件如下:

//
//  ViewController.h
//  通过加载plist文件来展示分组数据
//
//  Created by apple on 15/8/31.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//#import <UIKit/UIKit.h>@interface ViewController : UIViewController  <UITableViewDataSource>
@property (nonatomic,  strong) NSArray *groups;
@property (nonatomic,  strong) UITableView *tableView;
@end
编辑控制器类的.m文件如下:

//
//  ViewController.m
//  通过加载plist文件来展示分组数据
//
//  Created by apple on 15/8/31.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//#import "ViewController.h"
#import "group.h"
#define  WIDTH     [UIScreen mainScreen].bounds.size.width
#define  HEIGHT   [UIScreen mainScreen].bounds.size.height@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad
{[super viewDidLoad];// 新建一个UITableView组件self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];  //分配空间的同时设置分组风格self.tableView.dataSource = self; // 设置当前控制器为数据源对象[self.view addSubview:self.tableView];NSLog(@"%@",self.groups);
}// 重写数组groups的get方法实现懒加载,将字典转为模型
-(NSArray *)groups
{if (_groups == nil) {// 在app在手机安装的根目录下寻找plist文件的路径NSString *path = [[NSBundle mainBundle] pathForResource:@"cars_simple.plist" ofType:nil];// 读取文件的内容到一个数组NSArray *arrayDict = [NSArray arrayWithContentsOfFile:path];// 新建一个可变数组。用来存放每一个字典对象装换后的model对象NSMutableArray *modelGroup = [NSMutableArray array]; // 空的可变数组// 遍历从文件读取出来的字典数组,把每一个字典转换成model存放到可变数组modelGroup中for (NSDictionary *  dict  in   arrayDict) {Group *group = [Group groupWithDict:dict];[modelGroup addObject:group];}_groups = modelGroup;}return _groups;
}- (void)didReceiveMemoryWarning
{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.
}// 当前UITableView分为多少组
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{return self.groups.count;  // 数组的(字典——>模型)对象个数就是组数
}// 每一组分为多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{// 先获取组的对象Group *group = self.groups[section];return group.cars.count;
}// 每一组每一行显示什么内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{// 新建表格对象UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];// 获取组模型数据Group *group = self.groups[indexPath.section];// 用模型数据设置表格Cell属性cell.textLabel.text = group.cars[indexPath.row];return cell;
}// 添加组标题描述
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{// 获取model对象Group *group = self.groups[section];return group.title;
}// 添加组尾描述
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{// 获取model对象Group *group = self.groups[section];return group.desc;
}
@end
运行结果如下:








这篇关于iphone开发之表格组件UITableView的使用(三)通过加载plist文件字典转模型方式展示分组数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1115289

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.