数据库增删改查

配置 :
pod ‘AFNetworking’
pod ‘FMDB’
pod ‘SDWebImage’

在plist打开网络
App Transport Security Settings

在ViewController.h中,继承改为UITabBarController
在ViewController.m中:

#import “ViewController.h”
#import “oneViewController.h”
#import “twoViewController.h”
@interface ViewController ()

@end

@implementation ViewController

-(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//控制器
oneViewController *one =[[oneViewController alloc]init];

UINavigationController *onev =[[UINavigationController alloc]initWithRootViewController:one];

onev.tabBarItem =[[UITabBarItem alloc]initWithTitle:@"历史今天" image:[UIImage imageNamed:@""] selectedImage:[UIImage imageNamed:@""]];

twoViewController *two =[[twoViewController alloc]init];

UINavigationController *twov =[[UINavigationController alloc]initWithRootViewController:two];

twov.tabBarItem=[[UITabBarItem alloc]initWithTitle:@"我的收藏" image:[UIImage imageNamed:@""] selectedImage:[UIImage imageNamed:@""]];

self.viewControllers=@[onev,twov];

}

@end

1.创建三个页面
1.1首页页面
创建oneViewController继承于UIViewController

在oneViewController.m中:

#import “oneViewController.h”
#import <AFNetworking.h>
#import <FMDatabase.h>
#import “Model.h”
#import “mymodel.h”
#import “myTableViewCell.h”
#import “tiaoViewController.h”
@interface oneViewController ()<UITableViewDelegate , UITableViewDataSource>
@property(nonatomic , strong)UITableView *table;

@property(nonatomic , strong)NSMutableArray *dataSource;
@end
static NSString *oj = @“cell”;
@implementation oneViewController

-(void)viewDidLoad {

[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
self.navigationItem.title=@"我的";

//初始化数据
self.dataSource =[[NSMutableArray alloc]init];
// 设置表格
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:@"myTableViewCell" bundle:nil] forCellReuseIdentifier:oj];

// 加载数据
[self loadData];

}
-(void)loadData{

AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
[manager POST:@"http://c.m.163.com/nc/article/list/T1348648517839/0-20.html" parameters:self progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
          NSLog(@"zzz=====%@",responseObject);
          for (NSDictionary *dict in dic[@"T1348648517839"]) {
              
              Model *mo = [[Model alloc]init];
              [mo setValuesForKeysWithDictionary:dict];
              [self.dataSource addObject:mo];
              
          }
          
          NSLog(@"数据请求成功");
          [self.table reloadData];
          
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          NSLog(@"请求数据失败");
      }];

}

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

return self.dataSource.count;

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

myTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];

[cell loadData:self.dataSource[indexPath.row]];

return cell;

}

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

return 90;

}

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

[self.table deselectRowAtIndexPath:indexPath animated:YES];

Model *mo = self.dataSource[indexPath.row];

[[mymodel initData]initSql];
tiaoViewController *t=[tiaoViewController new];
t.mod=mo;
[self.navigationController pushViewController:t animated:YES];
[[mymodel initData]addData:mo];

[self.table reloadData];

}

@end

1.2收藏页面
创建twoViewController继承于UIViewController

在twoViewController.m中:

#import “twoViewController.h”
#import “mymodel.h”
#import “myTableViewCell.h”

@interface twoViewController ()<UITableViewDelegate , UITableViewDataSource>
@property(nonatomic , strong)UITableView *table;

@property(nonatomic , strong)NSMutableArray *dataSource;

@end
static NSString *bj = @“cell”;
@implementation twoViewController

-(void)viewDidLoad {

[super viewDidLoad];
self.view.backgroundColor=[UIColor whiteColor];
self.navigationItem.title=@"我的收藏";


// 初始化数组
self.dataSource = [[NSMutableArray alloc]init];

// 设置表格
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:@"myTableViewCell" bundle:nil] forCellReuseIdentifier:bj];

}
-(void)viewWillAppear:(BOOL)animated{

[[mymodel initData]initSql];


self.dataSource = [[mymodel initData]inquireArr];

[self.table reloadData];

}

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

return self.dataSource.count;

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

myTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:bj];
Model *model = self.dataSource[indexPath.row];
[cell loadData:model];
return cell;

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

return 90;

}

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

[[mymodel initData]initSql];

[[mymodel initData]deletData:[self.dataSource[indexPath.row]EdgID]];

[self.dataSource removeObject:self.dataSource[indexPath.row]];

[self.table reloadData];

}

@end

1.3详情页面
创建tiaoViewController继承于UIViewController

在tiaoViewController.h中:
#import <UIKit/UIKit.h>
#import “Model.h”
NS_ASSUME_NONNULL_BEGIN

@interface tiaoViewController : UIViewController
@property(nonatomic,strong)Model *mod;
@end

NS_ASSUME_NONNULL_END

在tiaoViewController.m:
#import “tiaoViewController.h”
#import <WebKit/WebKit.h>
#import “mymodel.h”
@interface tiaoViewController ()

@end

@implementation tiaoViewController

-(void)viewDidLoad {

[super viewDidLoad];
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKWebView *web=[[WKWebView alloc]initWithFrame:self.view.frame configuration:config];
NSURL *webUrl = [NSURL  URLWithString:@"http://mini.eastday.com/mobile/190307074045529.html"];
//创建请求对象
NSURLRequest *requset = [NSURLRequest requestWithURL:webUrl];
[web loadRequest:requset];
[self.view addSubview:web];

}
-(void)rightclick{

[[mymodel initData]initSql];
[[mymodel initData]addData:self.mod];
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"已收藏" style:UIBarButtonItemStyleDone target:self action:nil];

}

@end

2.创建Model继承于NSObject
2.1在Model.h中:
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Model : NSObject
@property(nonatomic,copy)NSString *imgsrc;
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *ptime;
@property(nonatomic,copy)NSString *url;
@property(nonatomic,assign)NSInteger classid;
// 设置一个主键ID
@property(nonatomic,assign)NSInteger EdgID;
@end

NS_ASSUME_NONNULL_END

2.2在Model.h中:
#import “Model.h”

@implementation Model
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
@end

3.创建mymodel继承于NSObject
3.1在mymodel.h中:
#import <Foundation/Foundation.h>
#import “Model.h”
NS_ASSUME_NONNULL_BEGIN

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

NS_ASSUME_NONNULL_END

3.2在mymodel.h中:
#import “mymodel.h”
#import <FMDatabase.h>
static mymodel *sql;
static FMDatabase *db;
@implementation mymodel
// 初始化单利方法
+(instancetype)initData{

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

return sql;

}

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

// 获取Documents文件目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// 拼接路径
NSString *fileName = [str stringByAppendingString:@"/new2.db"];

db = [[FMDatabase alloc]initWithPath:fileName];

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

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

}

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

//初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型);
[db executeUpdate:@"create table if not exists HistroyModel(HistroyID integer primary key,title text,imgsrc text,ptime text,url text)"];
NSLog(@"打开成功");

}

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

if ([db open]) {
    
    [db executeUpdate:[NSString stringWithFormat:@"insert into HistroyModel values(null,'%@','%@','%@','%@')",data.title,data.imgsrc,data.ptime ,data.url]];
    NSLog(@"插入成功");
    
}else{
    
    NSLog(@"插入失败");
    
}

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

}

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

if ([db open]) {
    
    [db executeUpdate:[NSString stringWithFormat:@"delete from HistroyModel where HistroyID=%ld",theid]];
    
    NSLog(@"删除成功");
    
}else{
    
    NSLog(@"删除失败");
    
}
// 关闭数据库
[db close];

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

// 创建数组
NSMutableArray *arr = [[NSMutableArray alloc]init];
// 创建集合
FMResultSet *set = [[FMResultSet alloc]init];

if ([db open]) {
    
    set = [db executeQuery:@"select * from HistroyModel"];
    
    while ([set next]) {
        
        Model *mod = [[Model alloc]init];
        mod.EdgID = [set intForColumn:@"HistroyID"];
        mod.classid = [set intForColumn:@"classid"];
        mod.title = [set stringForColumn:@"title"];
        mod.imgsrc = [set stringForColumn:@"imgsrc"];
        mod.ptime = [set stringForColumn:@"ptime"];
        mod.url=[set stringForColumn:@"url"];
        [arr addObject:mod];
    }
    
    
}else{
    
    NSLog(@"查询失败");
    
}

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

return arr;

}
// 关闭数据库
-(void)closeSql{

}

@end

4.创建myTableViewCell继承于UITableViewCell,选中xib
4.1在myTableViewCell.h中:
#import <UIKit/UIKit.h>
#import “Model.h”
NS_ASSUME_NONNULL_BEGIN

@interface myTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titlelable;
@property (weak, nonatomic) IBOutlet UILabel *deslable;
@property (weak, nonatomic) IBOutlet UIImageView *img;

-(void)loadData:(Model *)model;
@end

NS_ASSUME_NONNULL_END
4.2在myTableViewCell.m中:
#import “myTableViewCell.h”
#import <UIImageView+WebCache.h>
@implementation myTableViewCell

-(void)loadData:(Model *)model{

if (model) {
    
    self.titlelable.text= model.title;
    self.deslable.text=model.url;
    [self.img sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
    
}

}
4.3在myTableViewCell.xib中拖控件:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值