FMDB的使用

废话不多说,直接上代码:

#import "NewsViewController.h"
#import "FMDatabase.h"
#import "NewsCell.h"
#import "NewsModel.h"


@interface NewsViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) FMDatabase *database;//数据库操作类
@property (nonatomic, strong) NSMutableArray *dataSourceArr;


@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSourceArr = [NSMutableArray arrayWithCapacity:8];
    [self customNaviBar];
    self.view.backgroundColor = RGB(238, 238, 238);

    [self requestData];

    //创建数据库
    [self createDataBase];

    //创建表
    [self createTable];

    //读取数据
    [self selectDataFromDataBase];



}

- (void)createDataBase {

    //数据库操作对象
    self.database = [FMDatabase databaseWithPath:[self getFilePath]];

}
//创建表
- (void)createTable {

    if (![self.database open]) {
        return;
    }

    [self.database executeUpdate:@"create table if not exists NewsModel (news_id integer primary key autoincrement, news_newsId text, news_content text, news_createtime text)"];

    //3.关闭数据库
    [self.database close];
}

- (void)selectDataFromDataBase {

    //1.打开数据库
    if (![self.database open]) {
        return;
    }
    //2.通过SQL语句执行查询操作
    FMResultSet *result = [self.database executeQuery:@"select * from NewsModel"];
    while ([result next]) {
        NSString *newsID  = [result stringForColumn:@"news_newsId"];
        NSString *content = [result stringForColumn:@"news_content"];

        NSString *createtime = [result stringForColumn:@"news_createtime"];

        //把数据封装到对象里
        NewsModel *model = [[NewsModel alloc] initWithNewsId:newsID content:content createtime:createtime];
        //存放到数组中
        [self.dataSourceArr addObject:model];

    }

    //3.关闭数据库
    [self.database close];

}

//插入一条数据
- (void)insertIntoDataBaseWithModel:(NewsModel *)model{
    //1.打开数据库
    if (![self.database open]) {
        return;
    }
    //2.通过SQL语句操作数据库(即插入一条数据)
     [self.database executeUpdate:@"insert into NewsModel(news_newsId, news_content, news_createtime) values(?, ?, ?)", model.id, model.content, model.createtime];

    //3.关闭数据库
    [self.database close];
}


//删除一条数据
- (void)deleteFromDataBaseWithModel:(NewsModel *)model{
    //1.打开数据库
    BOOL isOpen = [self.database open];
    //2.执行SQL语句操作数据库 -- 删除操作
    if (!isOpen) {
        return;
    }
    [self.database executeUpdate:@"delete from NewsModel where news_newsId = ?", model.id];
    //3.关闭数据库
    [self.database close];
}

- (NSString *)getFilePath {

    //缓存文件夹的路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    //拼接上数据文件的路径

    return [path stringByAppendingPathComponent:@"News.sqlite"];
}


- (void)setupViews {

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWight, kHeight - 64 * kHMulriple) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self                 
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = RGB(238, 238, 238);
    [self.view addSubview:self.tableView];

    [self.tableView registerClass:[NewsCell class] forCellReuseIdentifier:@"NewsCell"];
  }
}

- (void)requestData {

    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@"加载中..."];

    WS(weakself);
    [HttpHelper requestUrl:KMessage_url success:^(id json) {

        [SVProgressHUD dismiss];
        NSArray *dataArr = json[@"data"];
        for (NSDictionary *dic in dataArr) {
            //model赋值        
            NewsModel *model = [[NewsModel alloc] initWithNewsId:dic[@"id"] content:dic[@"content"] createtime:dic[@"createtime"]];
            //更新数据库
            [weakself insertIntoDataBaseWithModel:model];
            [self.dataSourceArr addObject:model];
        }
        [self.tableView reloadData];
        [self setupViews];



    } failure:^(NSError *error) {

    }];

}
//数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"reuseIdentifier";

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    if (!cell) {

        cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    }
    NewsCell *newsCell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
    NewsModel *model = self.dataSourceArr[indexPath.row];
    newsCell.model = model;
    newsCell.backgroundColor = RGB(238, 238, 238);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsModel *model = self.dataSourceArr[indexPath.row];
    return [NewsCell heightForRowWithModel:model];
}
//删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //1.数据源
        NewsModel *model = self.dataSourceArr[indexPath.row];
        //从数组中删除
        [self.dataSourceArr removeObjectAtIndex:indexPath.row];

        //从数据库删除该条数据
        [self deleteFromDataBaseWithModel:model];


        //2.界面
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    } else if (editingStyle == UITableViewCellEditingStyleInsert) {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值