FMDB

先导入fmdb库
修改跟视图
在LoadData.h文件中

#import <Foundation/Foundation.h>
#import "User.h"

@interface LoadData : NSObject <NSCopying,NSMutableCopying>
//分享单例对象
+ (instancetype)shareLoadData;
//增加数据
- (void)insertData:(User *)usr;
//获取所有数据
- (NSArray *)queryData;
//删除数据
- (void)deleteData:(User *)usr;
@end

LoadData.m中

#import "LoadData.h"
#import "FMDB.h"
@interface LoadData()
{
    //定义数据库指针
    FMDatabase *db;
}
//创建数据库
- (void)createDataBase;
//创建数据表
- (void)createTable;
//关闭数据库
- (void)closeDataBase;
@end
//定义静态全局变量
static LoadData *ld;
@implementation LoadData
//分享单例对象
+ (instancetype)shareLoadData
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ld = [[LoadData alloc]init];
    });
    return ld;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (!ld) {
        ld = [[super allocWithZone:zone]init];
    }
    return ld;
}
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
    return self;
}
//创建数据库
- (void)createDataBase
{
    //获取数据库路径
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dbPath = [[arr lastObject]stringByAppendingPathComponent:@"data.db"];
    //创建数据库
    db = [FMDatabase databaseWithPath:dbPath];
}
//创建数据表
- (void)createTable
{
    
    //打开数据库
    [db open];
    //创建数据表
    NSString *sql = @"create table if not exists UserTable(id integer primary key autoincrement,phoneNum integer,password integer,name text)";
    [db executeUpdate:sql];
    //关闭数据库
    [self closeDataBase];
}
//关闭数据库
- (void)closeDataBase
{
    [db close];
}
//增加数据
- (void)insertData:(User *)usr
{
    //打开数据库
    [db open];
    //添加数据
    NSString *sql = [NSString stringWithFormat:@"insert into UserTable(phoneNum,password,name) values('%ld','%ld','%@')",usr.phoneNum,usr.password,usr.name];
    [db executeUpdate:sql];
    //关闭数据库
    [self closeDataBase];
}
//获取所有数据
- (NSArray *)queryData
{
    //创建数据库
    [self createDataBase];
    //创建数据表
    [self createTable];
    //打开数据库
    [db open];
    //获取所有数据
    NSMutableArray *mArr = [NSMutableArray array];
    NSString *sql = @"select * from UserTable";
    FMResultSet *set =[db executeQuery:sql];
    while ([set next]) {
        User *usr = [[User alloc]init];
        usr.idNum = [[set stringForColumn:@"id"]integerValue];
        usr.phoneNum = [[set stringForColumn:@"phoneNum"]integerValue];
        usr.password = [[set stringForColumn:@"password"]integerValue];
        usr.name = [set stringForColumn:@"name"];
        [mArr addObject:usr];
    }
    //关闭数据库
    [self closeDataBase];
    return [mArr copy];
}
//删除数据
- (void)deleteData:(User *)usr
{
    //打开数据库
    [db open];
    //删除数据
    NSString *sql = [NSString stringWithFormat:@"delete from UserTable where id = '%ld'",usr.idNum];
    [db executeUpdate:sql];
    //关闭数据库
    [self closeDataBase];
}
@end

在ViewController.m中

#import "ViewController.h"
#import "LoadData.h"
#import "User.h"
#import "AddViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    //定义变量数组、表格
    NSArray *arr;
    UITableView *table;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航标题
    self.navigationItem.title = @"全部用户";
    //创建添加按钮
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(itemClicked)];
    self.navigationItem.rightBarButtonItem = addItem;
    //初始化表格
    table = [[UITableView alloc]initWithFrame:self.view.bounds];
    table.dataSource = self;
    table.delegate = self;
    [self.view addSubview:table];
}
- (void)viewWillAppear:(BOOL)animated
{
    //获取全部数据
    arr = [[LoadData shareLoadData]queryData];
    //刷新表格
    [table reloadData];
}

//设置导航按钮响应方法
- (void)itemClicked
{
    //跳转
    AddViewController *avc = [[AddViewController alloc]init];
    [self.navigationController pushViewController:avc animated:YES];
}
//设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}
//设置单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"cellid";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
    }
    User *usr = arr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"id:%ld---phone:%ld",usr.idNum,usr.phoneNum];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"name:%@---pwd:%ld",usr.name,usr.password];
    return cell;
}
//设置删除单元格响应方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除数据
        [[LoadData shareLoadData]deleteData:arr[indexPath.row]];
        //重新获取全部数据
        arr = [[LoadData shareLoadData]queryData];
        //刷新表格
        [table reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

在AddViewController.m

#import "AddViewController.h"
#import "LoadData.h"
#import "User.h"

@interface AddViewController ()
{
    //定义变量手机号、密码、姓名文本框
    UITextField *phoneNumTF,*passwordTF,*nameTF;
}
@end

@implementation AddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NSArray *arr = @[@"手机号:",@"密码:",@"姓名:"];
    for (int i = 0,y = 90; i < 3; i ++) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(20, y, 80, 44)];
        lab.text = arr[i];
        [self.view addSubview:lab];
        y += 60;
    }
    //初始化手机号文本框
    phoneNumTF = [[UITextField alloc]initWithFrame:CGRectMake(100, 90, 200, 44)];
    phoneNumTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:phoneNumTF];
    //初始化密码文本框
    passwordTF = [[UITextField alloc]initWithFrame:CGRectMake(100, 150, 200, 44)];
    passwordTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:passwordTF];
    //初始化姓名文本框
    nameTF = [[UITextField alloc]initWithFrame:CGRectMake(100, 210, 200, 44)];
    nameTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:nameTF];
    //创建按钮
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(180, 300, 60, 44)];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

//设置按钮响应方法
- (void)btnClicked
{
    //加入正则表达式判断
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:phoneNumTF.text] == YES) || ([regextestcm evaluateWithObject:phoneNumTF.text] == YES) || ([regextestct evaluateWithObject:phoneNumTF.text] == YES) || ([regextestcu evaluateWithObject:phoneNumTF.text] == YES)){
        //插入数据
        User *usr = [[User alloc]init];
        usr.phoneNum = [phoneNumTF.text integerValue];
        usr.password = [passwordTF.text integerValue];
        usr.name = nameTF.text;
        [[LoadData shareLoadData]insertData:usr];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        //提示
        UIAlertController *alc = [UIAlertController alertControllerWithTitle:@"警告" message:@"手机号码不正确!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alc addAction:act];
        [self presentViewController:alc animated:YES completion:nil];
    }
}

@end

在User.h中

#import <Foundation/Foundation.h>

@interface User : NSObject
//定义属性ID、手机号、密码、姓名
@property (nonatomic,assign)NSInteger idNum,phoneNum,password;
@property (nonatomic,strong)NSString *name;
@end

在User.m中

#import "User.h"

@implementation User

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容