Oc 数据持久化Plist、SQLite、CoreData、FMDB四种-demo

第三方:FMDB(数据库)、MBProgressHUD(提示框)

PCH文件(个工程的条件预编译的头文件)
Project.pch

#ifndef Project_pch
#define Project_pch

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.

#import "DataBase.h"
#define My_Country @"中国"
#import "MBProgressHUD.h"
#import "User.h"
#endif /* Project_pch */

AppDelegate.m

#import "AppDelegate.h"
#import "ShowViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    ShowViewController *showVc = [[ShowViewController alloc]init];
    
    showVc.navigationItem.title = @"全部用户";
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:showVc];
    
    self.window.rootViewController = nav;
    
   
    return YES;
}

业务类:DataBase(文件)

DataBase.h

#import 
//协议
@protocol DataBase 
///添加
- (BOOL)addNew:(id)newObj;
///删除
- (BOOL)deleteOne:(id)deleteobj;
///修改
- (BOOL)updataOne:(id)upObj;
///获取所有
- (id)getAllObjects;
///是否重复
@optional
- (BOOL)objExist:(id)obj;
@end

PlistDataBase.h

 #import 

@interface PlistDataBase : NSObject

@end     

PlistDataBase.m

#import "PlistDataBase.h"
#import "User.h"
@implementation PlistDataBase
//私有方法,持久化数据的文件的路径设置
- (NSString *)filePath
{
    //获取沙盒中Documents目录的路径的字符串
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"%@",documentsPath);
    //设置持久化文件的路径
    NSString *fPath = [documentsPath stringByAppendingPathComponent:@"users.plist"];
    return fPath;
    
    
    
}
///添加
- (BOOL)addNew:(User *)newObj
{
    //首次添加,持久化文件不存在,数据库为空
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self filePath]])
    {
        //用序列化类将Oc的自定义对象转换为二进制
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newObj];
        NSArray *arr = @[data];
        [arr writeToFile:[self filePath] atomically:YES];
        return YES;
    }
    
    //文件存在,数组的元素为空
    NSMutableArray *arr = [[NSMutableArray alloc]initWithContentsOfFile:[self filePath]];
    //数组元素为空
    if (arr.count == 0)
    {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newObj];
         [arr addObject:data];
         [arr writeToFile:[self filePath] atomically:YES];
         return YES;
    }
    
    //数组元素不为空,须判断手机号是不是存在,存在不可添加,不存在可以添加
    if ([self objExist:newObj])
    {
        return NO;
    }
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newObj];
    [arr addObject:data];
    [arr writeToFile:[self filePath] atomically:YES];
    return YES;
}
///删除
- (BOOL)deleteOne:(User *)deleteobj
{
    //从文件中读取所有的二进制对象数据,存入数组中
    NSMutableArray *arr = [[NSMutableArray alloc]initWithContentsOfFile:[self filePath]];
    //将参数User *对象转换为NSData数据
    NSData *deletdata = [NSKeyedArchiver archivedDataWithRootObject:deleteobj];
    //从数组中删除该数据
    [arr removeObject:deletdata];
    //数组重新写入文件
    [arr writeToFile:[self filePath] atomically:YES];
    
    return YES;
}
///修改
- (BOOL)updataOne:(User *)upObj
{
    //获取持久化的数据
    NSMutableArray *arr = [[NSMutableArray alloc]initWithContentsOfFile:[self filePath]];
    
    NSInteger index = [self getObjIndexByPhone:upObj.phone];
    [arr replaceObjectAtIndex:index withObject:[NSKeyedArchiver archivedDataWithRootObject:upObj]];
    
    return [arr writeToFile:[self filePath] atomically:YES];
}
///获取所有
- (id)getAllObjects
{
    //文件不存在
    if (![[NSFileManager defaultManager]fileExistsAtPath:[self filePath]])
    {
        return nil;
    }
    //文件存在,从文件中读出数组
    NSArray *arr = [[NSArray alloc]initWithContentsOfFile:[self filePath]];
    //把二进制的数组用对象的数组返回使用
    NSMutableArray *userArr = [[NSMutableArray alloc]init];
    for (NSData *data in arr)
    {
        User *u = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [userArr addObject:u];
    }
    return userArr;
}
#pragma mark - 私有方法
///是否重复
- (BOOL)objExist:(User *)obj
{
    //读出文件中的所有数据
    NSArray *arr = [[NSArray alloc]initWithContentsOfFile:[self filePath]];
    for (NSData *data  in arr)
    {
        //使用反序列化类将二进制数据转换为User对象
        User *u = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if ([u.phone isEqualToString:obj.phone])
        {
            return YES;
        }
    }
    
    return NO;
}


/// 通过User对象的唯一手机号,找到该对象在数组中的下标
- (NSInteger)getObjIndexByPhone:(NSString *)phone
{
    NSArray *arr = [[NSArray alloc]initWithContentsOfFile:[self filePath]];
    for (int i = 0;i

SQLiteDataBase.h

#import 

@interface SQLiteDataBase : NSObject
- (BOOL)creatTableByName:(NSString *)name;

+(instancetype)defaultDataBase;
@end

SQLiteDataBase.m

#import "SQLiteDataBase.h"
#import 
#define USER_PATH @"users.db" //数据库文件的名称
static SQLiteDataBase *_dataBase = nil;


//延展
@interface SQLiteDataBase()
{
    sqlite3 *_db; // 操作数据库内存的指针
    NSString *_tableName; //表名字符串
}

@end



@implementation SQLiteDataBase

#pragma  mark  -单例类的方法
//重写allocWithZone方法,让外部文件使用alloc方法创建对象时,只得到一块内存空间
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (_dataBase == nil)
    {
        _dataBase = [super allocWithZone:zone];
    }
    return _dataBase;
}

+(instancetype)defaultDataBase
{
    if (_dataBase == nil)
    {
        _dataBase = [[SQLiteDataBase alloc]init];
    }
    return _dataBase;
}
- (id)copy
{
    return self;
}
- (id)mutableCopy
{
    return self;
}
#pragma  mark - 私有方法
//打开数据库
- (BOOL)openDB:(NSString *)dbPath
{
    //打开数据库
    //如果数据库文件不存在,先创建再打开,如果存在,直接打开
    //参数1 - 持久化文件的路径字符串
    NSString *fPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:dbPath];
    NSLog(@"db文件%@",fPath);
   int res =  sqlite3_open(fPath.UTF8String, &_db);
    if (res == SQLITE_OK)
    {
        return YES;
    }
    else
        return NO;
}
///关闭数据库
- (void)closeDB
{
    sqlite3_close(_db);
}

///创建一个数据表
- (BOOL)creatTableByName:(NSString *)name
{
    _tableName = name;
   BOOL success =  [self openDB:USER_PATH];
    if (!success) {
        [self closeDB];
        return NO;
    }
    
    //执行创建数据表操作
    // 1)先做一个sql语句
    //UNIQUE 唯一约束  PRIMARY KEY 主键自增
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE %@ (id INTEGER PRIMARY KEY AUTOINCREMENT,phone TEXT UNIQUE,name TEXT,password TEXT)",name];
    //2)定义一个预编译指针,用于存储编译结果
    sqlite3_stmt *statement = NULL;
    //3)执行编译操作,将sql语句转换为机器可以读懂的机器码
    sqlite3_prepare_v2(_db, sql.UTF8String, -1, &statement,NULL);
    //4)执行编译结果
    int res = sqlite3_step(statement);
    //5)释放预编译指针指向的内存
    sqlite3_finalize(statement);
    //关闭数据库
    [self closeDB];

    return res == SQLITE_DONE ? YES :NO;
}

#pragma  mark - 对外公开的方法
///添加
- (BOOL)addNew:(User *)newObj
{
    if (![self openDB:USER_PATH])
    {
        [self closeDB];
        return NO;
    }
    
    // 1)先做一个sql语句
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ (phone,name,password) VALUES (?,?,?)",_tableName];
    //2)定义一个预编译指针,用于存储编译结果
    sqlite3_stmt *statement = NULL;
    //3)执行编译操作,将sql语句转换为机器可以读懂的机器码
    sqlite3_prepare_v2(_db, sql.UTF8String, -1, &statement,NULL);
    //4)绑定?号
    //参数1 - 预编译指针变量
    //参数2 - 第几个问号
    //参数3 - 绑定的数据
    //参数4 - 读取绑定数据的前几个字符,-1表示全部内容
    //参数5 - 短暂,固定两个选择
    sqlite3_bind_text(statement, 1, newObj.phone.UTF8String, -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement, 2, newObj.name.UTF8String, -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement, 3, newObj.password.UTF8String, -1, SQLITE_TRANSIENT);
    
    
    //4)执行编译结果
    int res = sqlite3_step(statement);
    //5)释放预编译指针指向的内存
    sqlite3_finalize(statement);
    //关闭数据库
    [self closeDB];
    
    return res == SQLITE_DONE ? YES :NO;
    
}
///删除
- (BOOL)deleteOne:(User *)deleteobj
{
    
    if (![self openDB:USER_PATH])
    {
        [self closeDB];
        return NO;
    }

    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE id = ?",_tableName];
    //2)定义一个预编译指针,用于存储编译结果
    sqlite3_stmt *statement = NULL;
    //3)执行编译操作,将sql语句转换为机器可以读懂的机器码
    sqlite3_prepare_v2(_db, sql.UTF8String, -1, &statement,NULL);
    
    sqlite3_bind_int(statement, 1, (int)deleteobj.ID);
    //4)执行编译结果
    int res = sqlite3_step(statement);
    //5)释放预编译指针指向的内存
    sqlite3_finalize(statement);
    //关闭数据库
    [self closeDB];
    
    return res == SQLITE_DONE ? YES :NO;
    
}
///修改
- (BOOL)updataOne:(User *)upObj
{
    
    if (![self openDB:USER_PATH])
    {
        [self closeDB];
        return NO;
    }
    
    NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET name = ?,password = ? WHERE id = ?",_tableName];
    //2)定义一个预编译指针,用于存储编译结果
    sqlite3_stmt *statement = NULL;
    //3)执行编译操作,将sql语句转换为机器可以读懂的机器码
    sqlite3_prepare_v2(_db, sql.UTF8String, -1, &statement,NULL);
    
    sqlite3_bind_text(statement, 1, upObj.name.UTF8String, -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement, 2, upObj.password.UTF8String,-1, SQLITE_TRANSIENT);
    sqlite3_bind_int(statement, 3, (int)upObj.ID);
    
    //4)执行编译结果
    int res = sqlite3_step(statement);
    //5)释放预编译指针指向的内存
    sqlite3_finalize(statement);
    //关闭数据库
    [self closeDB];
    
    return res == SQLITE_DONE ? YES :NO;
}
///获取所有
- (id)getAllObjects
{
    if (![self openDB:USER_PATH])
    {
        [self closeDB];
        return nil;
    }
    
    // 1)先做一个sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT *FROM %@",_tableName];
    //2)定义一个预编译指针,用于存储编译结果
    sqlite3_stmt *statement = NULL;
    //3)执行编译操作,将sql语句转换为机器可以读懂的机器码
    sqlite3_prepare_v2(_db, sql.UTF8String, -1, &statement,NULL);
    //4)每行每行的读取数据
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    
    while (sqlite3_step(statement) == SQLITE_ROW)
    {
        int ID = sqlite3_column_int(statement, 0);
        const char *phone = (const char *)sqlite3_column_text(statement, 1);
        const char *name = (const char *)sqlite3_column_text(statement, 2);
        const char *pwd = (const char *)sqlite3_column_text(statement, 3);
        
        User *u = [[User alloc]init];
        u.ID = ID;
        u.phone = [NSString stringWithUTF8String:phone];
        u.name = [NSString stringWithUTF8String:name];
        u.password = [NSString stringWithUTF8String:pwd];
        [arr addObject:u];
        
    }
    //5)释放预编译指针指向的内存
    sqlite3_finalize(statement);
    //关闭数据库
    [self closeDB];

    return arr;
}

@end

CoreDataBase.h

#import 

@interface CoreDataBase : NSObject

@end

CoreDataBase.m

#import "CoreDataBase.h"
#import "User.h"
#import "AppDelegate.h"
#import "UserEntity+CoreDataClass.h"
@interface CoreDataBase ()
{
    AppDelegate *_app;
}
@end
@implementation CoreDataBase

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    }
    return self;
}
///添加
- (BOOL)addNew:(User *)newObj
{
    if ([self objExist:newObj])
    {
        return NO;
    }
    UserEntity *user = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([UserEntity class]) inManagedObjectContext:_app.persistentContainer.viewContext];
    user.id = (int)newObj.ID;
    user.name = newObj.name;
    user.phone = newObj.phone;
    user.password = newObj.password;
    
    //执行保存
    NSError *error = nil;
    BOOL res = [_app.persistentContainer.viewContext save:&error];
    if (error != nil)
    {
        NSLog(@"error %@",error);
    }
    return res;
    
    
}
///删除
- (BOOL)deleteOne:(User *)deleteobj
{
    //设置要抓取的实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([UserEntity class]) inManagedObjectContext:_app.persistentContainer.viewContext];
    //实例化抓取对象
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    [request setEntity:entity];
    //开始抓取
    NSArray *arr = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    
    UserEntity *deleEntity = nil;
    for (UserEntity *u in arr)
    {
        if (u.id == deleteobj.ID &&[u.name isEqualToString:deleteobj.name]&& [u.password isEqualToString:deleteobj.password]&&[u.phone isEqualToString:deleteobj.phone])
        {
            deleEntity = u;
            
            
            break;
        }
    }
    [_app.persistentContainer.viewContext deleteObject:deleEntity];
    return [_app.persistentContainer.viewContext save:nil];
    
}
///修改
- (BOOL)updataOne:(User *)upObj
{
    //设置要抓取的实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([UserEntity class]) inManagedObjectContext:_app.persistentContainer.viewContext];
    //实例化抓取对象
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    [request setEntity:entity];
    //开始抓取
    NSArray *arr = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    BOOL res = NO;
    
    for (UserEntity *u in arr)
    {
        if ([u.phone isEqualToString:upObj.phone])
        {
            u.name = upObj.name;
            u.password = upObj.password;
            u.id = (int)upObj.ID;
            res = [_app.persistentContainer.viewContext save:nil];
            break;
        }
    }
    return res;
    
}
///获取所有
- (id)getAllObjects
{
    //设置要抓取的实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([UserEntity class]) inManagedObjectContext:_app.persistentContainer.viewContext];
    //实例化抓取对象
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    [request setEntity:entity];
    //开始抓取
    NSArray *arr = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    NSMutableArray *usersArr = [[NSMutableArray alloc]init];
    for (UserEntity *u in arr)
    {
        User *user = [[User alloc]init];
        user.ID = u.id;
        user.name = u.name;
        user.phone  = u.phone;
        user.password = u.password;
        [usersArr insertObject:user atIndex:0];
    }
    return usersArr;
}
///是否重复
- (BOOL)objExist:(User *)obj
{
    //设置要抓取的实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([UserEntity class]) inManagedObjectContext:_app.persistentContainer.viewContext];
    //实例化抓取对象
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    
    [request setEntity:entity];
    //开始抓取
    NSArray *arr = [_app.persistentContainer.viewContext executeFetchRequest:request error:nil];
    
    for (UserEntity *u in arr)
    {
        if ([u.phone isEqualToString:obj.phone])
        {
            return YES;
        }
    }
    return NO;
}
@end

FMDataBase.h

#import 

@interface FMDataBase : NSObject

//声明类方法,让外部类获取该单例类的内存
+ (instancetype)defaultDB;
@end

FMDataBase.m

#import "FMDataBase.h"
#import "FMDB.h"
#import "User.h"
static FMDataBase *_staticFMDB = nil;
//延展
@interface FMDataBase ()
@property (nonatomic,strong)FMDatabase *db;
@end

@implementation FMDataBase
#pragma mark - 单例类方法
//单例类
+ (instancetype)defaultDB
{
    if (_staticFMDB == nil)
    {
        _staticFMDB = [[FMDataBase alloc]init];
        
    }
    return _staticFMDB;
}
//重写allocWithZone:方法,防止alloc生成新内存,方法返回的还是同一个对象
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (!_staticFMDB)
    {
        _staticFMDB = [super allocWithZone:zone];
    }
    return _staticFMDB;
}
//重写copy,mutableCopy方法,防止在外部类中使用copy,mutableCopy时运行崩溃,同时也防止新内存生成
- (id)copy
{
    return self;
}
- (id)mutableCopy
{
    return self;
}
#pragma mark - init方法重写
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createDB];
        [self initTable];
    }
    return self;
}
#pragma Mark - 创建数据库和数据表
//创建数据库
- (void)createDB
{
    //设置持久化文件的路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject ]stringByAppendingPathComponent:@"datas.db"];
    self.db = [FMDatabase databaseWithPath:path];
    
}
//创建数据表
- (void)initTable
{
    if(![self.db open])
    {
        [self.db close];
        return;
    }
    [self.db executeUpdate:@"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,password TEXT,phone TEXT UNIQUE)"];
    [self.db close];
    
}
#pragma mark - 控制器调用方法
///添加
- (BOOL)addNew:(User *)newObj{
    if (![self.db open])
    {
        [self.db close];
        return NO;
    }
    BOOL success = [self.db executeUpdateWithFormat:@"INSERT INTO users (name,password,phone) VALUES (%@,%@,%@)",newObj.name,newObj.password,newObj.phone];
    
    [self.db close];
    return success;
}
///删除
- (BOOL)deleteOne:(User *)deleteobj{
    if (![self.db open])
    {
        [self.db close];
        return NO;
    }
    BOOL success = [self.db executeUpdateWithFormat:@"DELETE FROM users WHERE id = %d" ,(int)deleteobj.ID];
    [self.db close];
    return success;
}
///修改
- (BOOL)updataOne:(User *)upObj{
    if (![self.db open])
    {
        [self.db close];
        return NO;
    }
    BOOL success = [self.db executeUpdateWithFormat:@"UPDATE users SET name = %@,password = %@ WHERE id = %ld",upObj.name,upObj.password,upObj.ID];
    
    [self.db close];
    return success;

}
///获取所有
- (id)getAllObjects{
    
    if (![self.db open])
    {
        [self.db close];
        return nil;
    }
    FMResultSet * set = [self.db executeQuery:@"SELECT * FROM users"];
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    while ([set next])
    {
        User *u = [[User alloc]init];
        u.ID = [set intForColumnIndex:0];
        u.name = [set stringForColumnIndex:1];
        u.password = [set stringForColumnIndex:2];
        u.phone = [set stringForColumnIndex:3];
        
        //[arr addObject:u];
        [arr insertObject:u atIndex:0];
        
    }
    [self.db close];
    return arr;
}

@end

模型类:Model(文件)

User.h

#import 

@interface User : NSObject
@property (nonatomic,strong)NSString *phone;
@property (nonatomic,strong)NSString *password;
@property (nonatomic,strong)NSString *name;
@property (nonatomic,assign)NSInteger ID;
@end

User.m

#import "User.h"

@implementation User

#pragma marl - NSCoder
//归档操作的两个必须实现的方法
//把对象的每个属性做成二进制数据
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.phone forKey:@"phone"];
    [aCoder encodeObject:self.password forKey:@"pwd"];
    [aCoder encodeObject:self.name forKey:@"name"];
}

//通过key将对象的每一个属性由二进制转换为Oc类型
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        self.phone = [aDecoder decodeObjectForKey:@"phone"];
        self.password = [aDecoder decodeObjectForKey:@"pwd"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
    }
    return self;
    
}

#pragma mark - NSCopy
//方法1 无需协议
- (id)copy
{
    User *u = [[User alloc]init];
    u.phone = self.phone;
    u.name = self.name;
    u.password = self.password;
    u.ID = self.ID;
    
    return u;
}
//方法2
//浅复制
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

@end

控制器类:Controller(文件)

ShowViewController.h

#import 

@interface ShowViewController : UIViewController

@end

ShowViewController.m

#import "ShowViewController.h"
#import "AddViewController.h"
#import "PlistDataBase.h"
#import "User.h"
#import "DetailViewController.h"
#import "SQLiteDataBase.h"
#import "FMDataBase.h"
#import "CoreDataBase.h"
@interface ShowViewController ()
{
    NSMutableArray *_tableDataArr; //表格赋值数组
}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)AddViewController *addVc;
@property (nonatomic,strong)DetailViewController *detailVc;
@property (nonatomic,strong)id db; //数据库对象
@end

@implementation ShowViewController

#pragma  mark - 懒加载 ,属性getter重写
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tableView.delegate  =self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (AddViewController *)addVc
{
    if (!_addVc)
    {
        _addVc = [[AddViewController alloc]init];
        
    }
    return _addVc;
}

- (DetailViewController *)detailVc
{
    if (!_detailVc)
    {
        _detailVc = [[DetailViewController alloc]init];
        
    }
    return _detailVc;
}
- (id)db
{
    if (!_db)
    {
        //策略模式
        //_db = [[PlistDataBase alloc]init];
        
//        _db = [[SQLiteDataBase alloc]init];
//        [_db creatTableByName:@"users"];
        
        //_db = [[FMDataBase alloc]init];
        _db = [[CoreDataBase alloc]init];
        
}
    return _db;
}
//添加子视图
- (void)loadView
{
    [super loadView];
    //
    NSLog(@"%@",NSStringFromSelector(_cmd));
    [self.view addSubview:self.tableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addDidHandle:)];
    
    
}

- (void)addDidHandle:(id)sender
{
    [self.navigationController pushViewController:self.addVc animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"%@",NSStringFromSelector(_cmd));
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _tableDataArr = [self.db getAllObjects];
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableDataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifer = @"CELL";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
    }
    
    User *u = _tableDataArr[indexPath.row];
    cell.textLabel.text = u.phone;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"ID:%ld名字:%@密码:%@",u.ID,u.name,u.password];
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //删除底层数据
        [self.db deleteOne:_tableDataArr[indexPath.row]];
        //删除给表格赋值的数组中相对应的数据
        [_tableDataArr removeObjectAtIndex:indexPath.row];
        //删除单元格
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView reloadData];
    }
}
#pragma mark----UITableViewDelegate----
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.detailVc.passUser = _tableDataArr[indexPath.row];
    [self.navigationController pushViewController:self.detailVc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

AddViewController.h

#import 

@interface AddViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
- (IBAction)saveHandle:(id)sender;

@end

AddViewController.m

#import "AddViewController.h"
#import "User.h"
#import "PlistDataBase.h"
#import "SQLiteDataBase.h"
#import "FMDataBase.h"
#import "CoreDataBase.h"
@interface AddViewController ()
{
    MBProgressHUD *_hud;
}
@end

@implementation AddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _hud = [[MBProgressHUD alloc]init];
    [self.view addSubview:_hud];
    [_hud hide:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.phoneTF.text = @"";
    self.pwdTF.text = @"";
    self.nameTF.text=  @"";
}

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


- (IBAction)saveHandle:(id)sender {
    
    if (self.phoneTF.text.length == 0 || self.pwdTF.text.length == 0 || self.nameTF.text.length == 0)
    {
        //设置弹出框的样式
        _hud.mode = MBProgressHUDModeText;
        //设置提示文本
        _hud.labelText = @"输入的内容不能为空";
        //显示
        [_hud show:YES];
        //2秒后隐藏
        [_hud hide:YES afterDelay:2.0];
        return;
    }
    
    //id db = [[PlistDataBase alloc]init];
//    id db = [[SQLiteDataBase alloc]init];
    //id db = [[FMDataBase alloc]init];
      id db = [[CoreDataBase alloc]init];
    
    User *u = [[User alloc]init];
    u.phone = self.phoneTF.text;
    u.password  = self.pwdTF.text;
    u.name = self.nameTF.text;
    
    BOOL success = [db addNew:u];
    if (success) {
        //设置弹出框的样式
        _hud.mode = MBProgressHUDModeText;
        //设置提示文本
        _hud.labelText = @"添加成功!";
        //显示
        [_hud show:YES];
        [self performSelector:@selector(back:) withObject:nil afterDelay:2.0];
    }
    else
    {
        //设置弹出框的样式
        _hud.mode = MBProgressHUDModeText;
        //设置提示文本
        _hud.labelText = @"用户已存在!";
        //显示
        [_hud show:YES];
        //2秒后隐藏
        [_hud hide:YES afterDelay:2.0];

    }
    
}

- (void)back:(id)sender
{
    if (_hud.isHidden == NO)
    {
        [_hud hide:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];

    
}
@end

AddViewController.xib

Oc 数据持久化Plist、SQLite、CoreData、FMDB四种-demo_第1张图片
屏幕快照 2017-09-10 20.59.20.png

DetailViewController.h

#import 

@interface DetailViewController : UIViewController
@property (nonatomic,strong)User *passUser;
@end

DetailViewController.m

#import "DetailViewController.h"
#import "PlistDataBase.h"
#import "SQLiteDataBase.h"
#import "FMDataBase.h"
#import "CoreDataBase.h"
@interface DetailViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
- (IBAction)updataHandle:(id)sender;

@end

@implementation DetailViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.phoneTF.text = self.passUser.phone;
    self.pwdTF.text=  self.passUser.password;
    self.nameTF.text = self.passUser.name;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    
    
}

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



- (IBAction)updataHandle:(id)sender {
    
//    User *newU = [[User alloc]init];
//    
//    newU.ID = self.passUser.ID;
//    newU.phone = self.passUser.phone;
//    newU.password = self.pwdTF.text;
//    newU.name = self.nameTF.text;
    //这句话实现与上面4句代码等效的结果
    User *newU = [self.passUser copy];
    newU.password = self.pwdTF.text;
    newU.name = self.nameTF.text;
    
    //PlistDataBase *db = [[PlistDataBase alloc]init];
    
//    SQLiteDataBase *db = [[SQLiteDataBase alloc]init];

    //FMDataBase *db = [[FMDataBase alloc]init];
    CoreDataBase *db = [[CoreDataBase alloc]init];
    
    BOOL success = [db updataOne:newU];
    
    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hud];
    hud.removeFromSuperViewOnHide = YES;
    hud.mode = MBProgressHUDModeText;
    hud.labelText = success ? @"更新成功" :@"更新失败";
    [hud show:YES];
    [hud hide:YES afterDelay:2.0];
      
}
@end

DetailViewController.xib

Oc 数据持久化Plist、SQLite、CoreData、FMDB四种-demo_第2张图片
屏幕快照 2017-09-10 20.59.20.png

你可能感兴趣的:(Oc 数据持久化Plist、SQLite、CoreData、FMDB四种-demo)