FMDB

Model:
DataModel.h
// 设置一个主键ID
@property(nonatomic , assign)NSInteger classID;

// 图片
@property(nonatomic , strong)NSString *imgsrc;

// 标题
@property(nonatomic , strong)NSString *title;

// 跳转url
@property(nonatomic , strong)NSString *url;

DataModel.m
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

SqliteModel.h
// 单利方法
+(instancetype)initData;
// 初始化数据库
-(void)initSql;
// 初始化表格
-(void)initTable;
// 添加
-(void)addData:(DataModel *)data;
// 删除数据
-(void)deletData:(NSInteger)theid;
// 查询数据
-(NSMutableArray *)inquireArr;
// 关闭数据库
-(void)closeSql;

SqliteModel.m

// 创建静态变量
static SqliteModel *sql;
static FMDatabase *db;

@implementation SqliteModel

// 初始化单利方法
+(instancetype)initData{

if(!sql){
    
    sql = [[SqliteModel alloc]init];
    
}

return sql;

}

// 初始化数据库
-(void)initSql{

// 获取Documents目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// 拼接路径
NSString *fileName = [str stringByAppendingString:@"news.db"];
NSLog(@"file:%@",fileName);
// 创建数据库
db = [[FMDatabase alloc]initWithPath:fileName];

if([db open]){
    
    NSLog(@"打开数据库成功");
    // 初始化表格
    [self initTable];
    
}else{
    
    NSLog(@"打开数据库失败");
    
}

}

// 初始化表格
-(void)initTable{

//初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型);
[db executeUpdate:@"create table if not exists DataModel(classID integer primary key,imgsrc blob,title text,url text)"];
// 关闭数据库
[db close];

}

// 添加数据
-(void)addData:(DataModel *)data{

if ([db open]) {
    
    //添加数据的sql语句:insert into 表名 values(null,?,?);
    [db executeUpdate:[NSString stringWithFormat:@"insert into DataModel  values(null,'%@','%@','%@')",data.imgsrc,data.title,data.url]];
    NSLog(@"插入成功");
    //        NSLog(@"---------%@",data);
    
}else{
    
    NSLog(@"添加失败");
    
}
// 关闭数据库
[db close];

}

// 删除数据
-(void)deletData:(NSInteger)theid{

if ([db open]) {
    
    //sql 语句: delete from 表名 where 表名的主键id = ?
    [db executeUpdate:[NSString stringWithFormat:@"delete from DataModel where classID = %ld",theid]];
    NSLog(@"删除成功");
    
}else{
    
    NSLog(@"删除失败");
    
}

// 关闭数据库
[db close];

}

// 查询数据库
-(NSMutableArray *)inquireArr{

// 创建数据
NSMutableArray *arr = [NSMutableArray new];
// 集合
FMResultSet *set = [FMResultSet new];

if ([db open]) {
    //sql 语句格式:select *from 表名
    set = [db executeQuery:@"select *from DataModel"];
    // 判断有没有东西
    while ([set next]) {
        
        DataModel *model = [[DataModel alloc]init];
        model.imgsrc = [set stringForColumn:@"imgsrc"];
        model.title = [set stringForColumn:@"title"];
        model.url = [set stringForColumn:@"url"];
        model.classID = [set intForColumn:@"classID"];
        [arr addObject:model];
        
    }
    
}else{
    NSLog(@"查询失败");
}
[db close];
return arr;

}

-(void)closeSql{

}

@end

View:
NewsTableViewCell.h Xib
@property (weak, nonatomic) IBOutlet UIImageView *imgV;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

-(void)loadDataModel:(DataModel *)model;

NewsTableViewCell.m
-(void)loadDataModel:(DataModel *)model{

if(model){
    NSLog(@"title====%@",model.title);
    self.titleLabel.text = model.title;
    [self.imgV sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
}

}
@end

Controller
CollectViewController.h 没有东西 继承UIViewController

CollectViewController.m

#import “CollectViewController.h”

@interface CollectViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic , strong)UITableView *tbv;
@property(nonatomic , strong)NSMutableArray *arr;
@end

@implementation CollectViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @“收藏列表”;

    self.tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tbv.delegate =self;
    self.tbv.dataSource =self;
    [self.view addSubview:self.tbv];
    [self.tbv registerNib:[UINib nibWithNibName:@“NewsTableViewCell” bundle:nil] forCellReuseIdentifier:@“cell”];

}
//视图展示的时候 查询数据库 有没有信息 有展示出来
-(void)viewWillAppear:(BOOL)animated{

[[SqliteModel initData]initSql];
self.arr = [[SqliteModel initData]inquireArr];
for (DataModel *dd in self.arr) {
    NSLog(@"qqqq====%ld",dd.classID);
    
}
[self.tbv reloadData];

}

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“cell”];

[cell loadDataModel:self.arr[indexPath.row]];

return cell;

}

// 删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

[[SqliteModel initData]initSql];
NSLog(@"zzzz======%ld",[self.arr[indexPath.row]classID]);
[[SqliteModel initData]deletData:[self.arr[indexPath.row]classID]];
//删除数据
[self.arr removeObject:self.arr[indexPath.row]];

[self.tbv reloadData];

}

//点击跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

[self.tbv deselectRowAtIndexPath:indexPath animated:YES];
CollectNextViewController *collect = [CollectNextViewController new];
DataModel *data = self.arr[indexPath.row];
collect.model = data;
[self.navigationController pushViewController:collect animated:YES];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}

@end

CollectNextViewController.h
@property(nonatomic , strong)DataModel *model;

CollectNextViewController.m

#import “CollectNextViewController.h”

@interface CollectNextViewController ()

@end

@implementation CollectNextViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    //网页视图 ios12摒弃了uiwebview
    WKWebView *webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    //将urlString转换为url
    NSURL *url=[NSURL URLWithString:self.model.url];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //网页视图加载网页
    [webview loadRequest:request];
    //添加到当前视图上
    [self.view addSubview:webview];

}

@end

AppDelegate.m
ViewController *vc = [[ViewController alloc]init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
self.window.rootViewController = nav;

NextViewController.h 继承UIViewController
@property(nonatomic , strong)DataModel *model;

NextViewController.m

#import “NextViewController.h”

@interface NextViewController ()

@end

@implementation NextViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];
    //网页视图 ios12摒弃了uiwebview
    WKWebView *webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    //将urlString转换为url
    NSURL *url=[NSURL URLWithString:self.model.url];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //网页视图加载网页
    [webview loadRequest:request];
    //添加到当前视图上
    [self.view addSubview:webview];

}

-(void)collect{

[[SqliteModel initData]initSql];
// NSLog(@"=======%@",self.model);
[[SqliteModel initData]addData:self.model];

}

@end

PrefixHeader.pch

#import “DataModel.h”
#import “SqliteModel.h”
#import “NewsTableViewCell.h”
#import “CollectViewController.h”
#import “CollectNextViewController.h”
#import “ViewController.h”
#import “NextViewController.h”
#import <UIImageView+WebCache.h>
#import “AFNetworking.h”
#import “UIKit+AFNetworking.h”
#import <WebKit/WebKit.h>
#import “FMDatabase.h”
#import “SqliteModel.h”

#define YULE_PATH @“http://c.m.163.com/nc/article/list/T1348648517839/0-20.html
#define YULE_KEY @“T1348648517839”

#endif /* PrefixHeader_pch */

ViewController.m

#import “ViewController.h”

#import “MBProgressHUD.h”

@interface ViewController ()<UITableViewDelegate , UITableViewDataSource>{
NSMutableArray *dataSource;
}

@property(nonatomic , strong)UITableView *table;

@end

static NSString *oj = @“cell”;

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化
    dataSource = [[NSMutableArray alloc]init];

    self.title = @“数据库”;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];

    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource =self;
    [self.view addSubview:self.table];

    // 注册
    [self.table registerNib:[UINib nibWithNibName:@“NewsTableViewCell” bundle:nil] forCellReuseIdentifier:oj];

    [self loadData];

}

// 显示提示文本
-(void)showMBHudWithMessage:(NSString *)msg{

MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
// 设置文本的提示样式
hud.mode = MBProgressHUDModeIndeterminate;
// 自动从父视图移除
hud.removeFromSuperViewOnHide = YES;
hud.labelText = msg;
[self.view addSubview:hud];
[hud show:YES];
[hud hide:YES afterDelay:2.0];

}

-(void)loadData{

// 显示一个等待指示器
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
hud.removeFromSuperViewOnHide = YES;
[self.view addSubview:hud];
[hud show:YES];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:YULE_PATH parameters:self progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSDictionary *dict = responseObject;
    for (NSDictionary *dic in [dict objectForKey:@"T1348648517839"]) {
        
        DataModel *mod = [[DataModel alloc]init];
        mod.title = [dic objectForKey:@"title"];
        mod.url = [dic objectForKey:@"url"];
        mod.imgsrc = [dic objectForKey:@"imgsrc"];
        [self->dataSource addObject:mod];
        // 隐藏等待指示器
        [hud hide:YES];
        
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"数据请求成功");
        [self showMBHudWithMessage:@"加载成功"];
        [self.table reloadData];
    });
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"请求失败");
}];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(@"%@",dataSource);

NSLog(@"%ld",dataSource.count);
return dataSource.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];

[cell loadDataModel:dataSource[indexPath.row]];

return cell;

}

-(void)collect{

CollectViewController *collect = [[CollectViewController alloc]init];
[self.navigationController pushViewController:collect animated:YES];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 120;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

NextViewController *next = [[NextViewController alloc]init];
DataModel *data = dataSource[indexPath.row];
next.model = data;
[self.navigationController pushViewController:next animated:YES];

}
@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值