前提是已经知道了有哪些 key 值

Model 类:

.h

@interface ListModel : NSObject

@property (nonatomic, copy)NSString *time;
@property (nonatomic, copy)NSString *cname;
@property (nonatomic, copy)NSString *summary;
@property (nonatomic, copy)NSString *title;
@property (nonatomic, copy)NSString *type; - (void)createArray:(NSDictionary *)result
dataSource:(NSMutableArray *)dataSource;

.m

- (void)createArray:(NSDictionary *)result
dataSource:(NSMutableArray *)dataSource
{
UserModel *userModel = [[UserModel alloc]init];
NSArray *array = result[@"news"];
for (NSDictionary *dict in array) {
ListModel *listModel = [[ListModel alloc]init];
listModel.cname = [NSString stringWithFormat:@"%@",dict[@"cname"]];
listModel.summary = [NSString stringWithFormat:@"%@",dict[@"summary"]];
listModel.title = [NSString stringWithFormat:@"%@",dict[@"title"]];
listModel.type = [NSString stringWithFormat:@"%@",dict[@"type"]];
listModel.time = [NSString stringWithFormat:@"%@",dict[@"lastUpdateTime"]];
[dataSource addObject:listModel];
//NSLog(@"cname:%@",listModel.type); //时间戳转换为时间
NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[listModel.time integerValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yy-MM-dd"];
NSString *beginStr = [formatter stringFromDate:startDate];
listModel.time = beginStr;
if (!([userModel selectTable].count > )) {
[userModel insert:listModel];
}
}
}

FMDB:

- (BOOL)delteSqlite {
if ([self isSqliteExist]) {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error;
[manager removeItemAtPath:path error:&error];
if (error) {
NSLog(@"delete sqlite failed");
}else{
NSLog(@"delete sqlite success");
}
return YES;
}else{
NSLog(@"sqlite isn't exist");
return NO;
}
return NO;
} #pragma mark - 检测本地文件是否存在
- (BOOL)isSqliteExist {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:path]) {
NSLog(@"sqlite is exist");
return YES;
}else{
NSLog(@"sqlite isn't exist, prepare to create");
return NO;
}
} #pragma mark -- 建数据库
- (void)openDB {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSLog(@"path:%@",path);
_db = [FMDatabase databaseWithPath:path];
if ([_db open]) {
//建表
BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS NewsInfo(id integer PRIMARY KEY AUTOINCREMENT,cname text NOT NULL,summary text NOT NULL,title text NOT NULL,type text NOT NULL,time text NOT NULL)"];
if (result) {
NSLog(@"create table success");
}else{
NSLog(@"create tabble success");
[_db close];
}
}else{
[_db close];
NSLog(@"open db failed");
}
} #pragma mark - 查询数据库
- (NSMutableArray *)selectTable
{
if (![_db open]) {
[self openDB];
}
NSMutableArray *tempArray = [NSMutableArray array];
if ([_db open]) {
FMResultSet *resultSet = [_db executeQuery:@"select *from NewsInfo;"];
while ([resultSet next]) {
ListModel *listModel = [[ListModel alloc]init];
listModel.cname = [resultSet objectForColumnName:@"cname"];
listModel.summary = [resultSet objectForColumnName:@"summary"];
listModel.title = [resultSet objectForColumnName:@"title"];
listModel.type = [resultSet objectForColumnName:@"type"];
listModel.time = [resultSet objectForColumnName:@"time"];
[tempArray addObject:listModel];
}
[_db close];
}
return tempArray;
} #pragma mark - 插入进表
- (void)insert:(ListModel *)model
{
if (![_db open]) {
[self openDB];
}
[_db executeUpdate:@"INSERT INTO NewsInfo(cname,summary,title,type,time)VALUES(?,?,?,?,?)",model.cname,model.summary,model.title,model.type,model.time];
} #pragma mark - 修改某个值
- (void)update:(NSString *)value to:(NSString *)key {
if (![_db open]) {
[self openDB];
}
if ([_db open]) {
NSString *updateSql = [NSString stringWithFormat:@"update NewsInfo set %@='%@'",key,value];
BOOL res = [_db executeUpdate:updateSql]; if (!res) {
NSLog(@"error when insert db table");
} else {
NSLog(@"success to insert db table");
}
[_db close];
}
}

VC:

- (void)viewDidLoad {
[super viewDidLoad];
[self addBtn]; self.title = @"新闻";
_userModel = [[UserModel alloc]init];
_dataSource = [[NSMutableArray alloc]initWithCapacity:];
[self.view addSubview:self.tableView]; [self isRequestData];
} #pragma mark - 添加一个删除数据库的按钮
- (void)addBtn {
UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"delete" style:UIBarButtonItemStylePlain target:self action:@selector(deleteSqlite)];
self.navigationItem.rightBarButtonItem = item;
} #pragma mark 删除数据库按钮方法
- (void)deleteSqlite {
[_userModel delteSqlite];
} #pragma mark - 本地数据库有值就不请求数据,取本地数据库值
- (void)isRequestData {
if ([_userModel isSqliteExist]) {
_dataSource = [_userModel selectTable];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}else{
//创建一个异步队列解析 json,防止阻塞主线程
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, );
dispatch_async(queue, ^{
[self urlStr];
});
}
} #pragma mark -- 解析 JSON
- (void)urlStr
{
NSURL *url = [NSURL URLWithString:URLSTR];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSError *error1;
//解析 json,返回字典,这里解析出来是 unicode 编码,不影响正常显示
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error1]; ListModel *listModel = [[ListModel alloc]init];
[listModel createArray:dict dataSource:_dataSource]; //数据源开始是空的,因为网络等原因...等数据源有值了,在主线程刷新 TabelView
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}];
[task resume];
} #pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSource.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cell_id = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_id];
}
ListModel *listModel = _dataSource[indexPath.row];
cell.textLabel.text = listModel.title;
cell.detailTextLabel.text = listModel.time;
return cell;
} #pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ListModel *listModel = _dataSource[indexPath.row];
DetailViewController *detailVC = [[DetailViewController alloc]init];
[self.navigationController pushViewController:detailVC animated:YES];
detailVC.titleStr = listModel.cname;
detailVC.contentStr = listModel.summary;
} #pragma mark -- getter
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:self.view.frame];
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}

完整代码,见 github

iOS 学习 - 22 异步解析 JSON,使用 FMDB 存储,TableView 显示的更多相关文章

  1. 前端学习之——js解析json数组

    ** 前端学习之——js解析json数组** 解析json数组即对JSONArray的遍历 一.对于标准的json数组如: var result=[{"flag":1," ...

  2. iOS学习之数据解析

    解析:按照约定好的格式提取数据的过程叫做解析; 后台开发人员按照约定好的格式存入数据,前端开发人员按照约定的格式读取数据; 主流的格式: XML / JSON 前端和后台都能识别的格式;  XML解析 ...

  3. 《项目经验》--后台一般处理程序向前台JS文件传递JSON,JS解析JSON,将数据显示在界面--显示在DropDownList 或 显示在动态创建的table中

    http://blog.csdn.net/mazhaojuan/article/details/8599167 先看一下我要实现的功能界面: 这篇文章主要介绍:后台一般处理程序把从数据库查找的数据,转 ...

  4. iOS网络-02-数据解析(JSON与XML)

    数据交互格式 服务器返回给用户的数据,通常是以下两种方式: JSON XML JSON 一种轻量级的数据数据格式,体积比XML小,是服务器返回给移动端通常采用的格式 用使用JSON文件中的数据,需要对 ...

  5. 【原】iOS学习之XML与JSON两种数据结构比较和各自底层实现

    1.XML与JSON两种数据结构的优缺点 1> XML 优点:
 格式统一, 符合标准
 容易与其他系统进行远程交互, 数据共享比较方便 
 缺点: XML文件格式文件庞大, 格式复杂, 传输占 ...

  6. ANDROID_MARS学习笔记_S02_013_Gson解析json串

    1.MainActivity.java package com.json; import java.io.IOException; import java.io.StringReader; impor ...

  7. Python学习--22 异步I/O

    在同步IO中,线程启动一个IO操作然后就立即进入等待状态,直到IO操作完成后才醒来继续执行.而异步IO方式中,线程发送一个IO请求到内核,然后继续处理其他的事情,内核完成IO请求后,将会通知线程IO操 ...

  8. 【原】iOS学习之UIStoryboardSegue解析

    在 Storyboard 的可视化编程中,跳转界面就是按住 Ctrl 使用鼠标头一条连线就可以解决,相当的简单!本篇博客主要就是介绍这条连线,在iOS中,这条连线也是一个对象,也有其自己的初始化方法和 ...

  9. iOS学习22之视图控制器

    1.自定义视图 1> 概述   定义视图:系统标准UI之外,自己组合而出的新的视图. 定义视图的优点: iOS提供了很多UI组件,借助它们我们可以实现不同的功能.尽管如此,实际开发中,我们还需要 ...

随机推荐

  1. Deferred在jQuery和Angular中的使用与简单实现

    Deferred在jQuery和Angular中的使用与简单实现 Deferred是在jQuery1.5版本中加入的,并且jQuery使用它完全重写了AJax,以前也只是偶尔使用.但是上次在使用Ang ...

  2. ZOJ Problem Set - 1216 Deck

    #include <stdio.h> int main() { ]; double t=2.0; table[]=0.5; ;i<;i++) { t+=; table[i]=tabl ...

  3. Linux入门

    参考资料:http://www.92csz.com/study/linux/ [Linux系统目录结构] 登录系统后,在当前命令窗口下输入 ls / 你会看到 以下是对这些目录的解释: /bin bi ...

  4. LSM Tree存储组织结构介绍

    LSM Tree(Log Structured Merge Trees)数据组织方式被应用于多种数据库,如LevelDB.HBase.Cassandra等,下面我们从为什么使用LSM tree.LSM ...

  5. jQuery-1.9.1源码分析系列(十六)ajax——响应数据处理和api整理

    ajax在得到请求响应后主要会做两个处理:获取响应数据和使用类型转化器转化数据 a.获取响应数据 获取响应数据是调用ajaxHandleResponses函数来处理. ajaxHandleRespon ...

  6. Java进击C#——语法之面向对象

    本章简言 上一章笔者讲到关于ADO.NET相关的知识,知道了如何去访问数据库.本章将来讲关于面向对象的思想.不管在JAVA还是在C#面向对象思想的重要性都是占了一个很大的成份.往往他就像呼吸一样子,更 ...

  7. 用浏览器(支持WebSocket)和node-inspector 调试后端(CoffeeScript,Typescript)代码

    调试效果 配置 npm安装node-inspector: $ npm install -g node-inspector 配置gulp,gulp可以用 gulp-node-inspector 或 用g ...

  8. Js运动框架

    <!DOCTYPE html> <html> <head> <title></title> </head> <body&g ...

  9. Cocos2dx实现光影效果的两种方式

    Shader 和 RenderTexture 先贴上两张效果图 (Shader) (RenderTexture) 说一下实现的原因,因为项目中需要夜景,光影的效果.最初想到使用Shader来实现.实现 ...

  10. 无法解决 equal to 操作中 "SQL_Latin1_General_CP1_CI_AS" 和 "Chinese_PRC_CI_AS"

    无法解决 equal to 操作中 "SQL_Latin1_General_CP1_CI_AS" 和 "Chinese_PRC_CI_AS" 之间 2011-0 ...