Plist文件持久化

1.首先创建个模型类User类

.h


#import <Foundation/Foundation.h>

//因为是自定义的类,是用plist持久化须采用<NSCoding>协议
@interface User : NSObject<NSCoding>
@property(nonatomic,assign)NSInteger ID;
@property(nonatomic,strong)NSString *phone;
@property(nonatomic,strong)NSString *password;
@property(nonatomic,strong)NSString *name;
@end

.m


#import "User.h"

@implementation User

#pragma mark - NSCoding协议
//归档操作的两个必须实现的方法
//把对象的每一个属性对象作成二进制数据
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.phone forKey:@"phone"];
    [aCoder encodeObject:self.password forKey:@"password"];
    [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:@"password"];
        self.name = [aDecoder decodeObjectForKey:@"name"];
        
    }
    return self;
}

#pragma mark - NSCopying
-(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;
}

@end

2.创建一个业务类plistDataBase

.h

#import <Foundation/Foundation.h>

@protocol DataBase <NSObject>
@required
///添加
-(BOOL)addNew:(id)newObj;
///删除
-(BOOL)deleteOne:(id)deleteObj;
///修改
-(BOOL)updateOne:(id)upObj;
///查询
-(id)getAllobjects;
@optional
///是否重复
-(BOOL)objExist:(id)obj;
@end

.m

#import "PlistDataBase.h"
#import "User.h"
@implementation PlistDataBase
//私有方法,持久化数据的文件的路径设置
-(NSString *)filePath
{
    // 获取document路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"%@",documentPath);
    //设置持久化文件的路径
    NSString *fpath = [documentPath stringByAppendingPathComponent:@"user.plist"];
    return fpath;
}

///添加
-(BOOL)addNew:(User *)newObj
{
   //首次添加,持久化文件不存在,数据库为空
    if (![[NSFileManager defaultManager]fileExistsAtPath:[self filePath]]) {
    
        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) {
        [arr addObject:[NSKeyedArchiver archivedDataWithRootObject:newObj]];
        [arr writeToFile:[self filePath] atomically:YES];
        return YES;
    }
    
    //数组元素不为空,须判断手机号是不是存在,存在不可添加,不存在可以添加
    if ([self objExist:newObj]) {
        return NO;
    }
    
    [arr addObject:[NSKeyedArchiver archivedDataWithRootObject:newObj]];
    [arr writeToFile:[self filePath] atomically:YES];
    return  YES;
    
}

///删除
-(BOOL)deleteOne:(id)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)updateOne:(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 * 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 < arr.count; i ++) {
        NSData *data = arr[i];
        User *u = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        if ([u.phone isEqualToString:phone]) {
            return i;
        }
        
    }
    return -1;
}

@end

3.数据展示,创建一个ShowViewController

.h

#import <UIKit/UIKit.h>

@interface ShowViewController : UIViewController

@end

.m

#import "ShowViewController.h"
#import "AddViewController.h"
#import "PlistDataBase.h"
#import "DetailViewController.h"
#import "User.h"


@interface ShowViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    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.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}
-(DetailViewController *)detailVC
{
    if (!_detailVC) {
        _detailVC = [[DetailViewController alloc]init];
    }
    return _detailVC;
}
-(AddViewController *)addVC
{
    if (!_addVC) {
        _addVC = [[AddViewController alloc]init];
    }
    return _addVC;
}
-(id)db
{
    if (!_db) {
        //策略模式
      _db = [[PlistDataBase alloc]init];
    }
    return _db;
}
#pragma mark ------视图加载方法---------
//添加子视图
-(void)loadView
{
    [super loadView];
    
    NSLog(@"%@",NSStringFromSelector(_cmd));
    NSLog(@"%@",NSStringFromSelector(@selector(loadView)));
    [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)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _tableDataArr = [self.db getAllobjects];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",NSStringFromSelector(_cmd));
    // Do any additional setup after loading the view.
}

#pragma mark ---------UITableViewDataSource;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableDataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"CELLID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    User *u = _tableDataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"id:%ld---phone:%@",u.ID,u.phone];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"name---:%@\t\tpassword----:%@",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.u = _tableDataArr[indexPath.row];
    
    [self.navigationController pushViewController:self.detailVC animated:NO];
    
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

4.数据的添加 创建一个AddViewController

.h

#import <UIKit/UIKit.h>

@interface AddViewController : UIViewController

@end

.m

#import "AddViewController.h"
#import "PlistDataBase.h"
#import "User.h"
#import "MBProgressHUD.h"


@interface AddViewController ()
{
    MBProgressHUD *_hud; //第三方
}
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

- (IBAction)saveHandle:(id)sender;

@end

@implementation AddViewController

-(void)viewWillAppear:(BOOL)animated
{
// 文本清空
    [super viewWillAppear:animated];
    self.phoneTF.text = @"";
    self.nameTF.text = @"";
    self.passwordTF.text = @"";
}
-(void)viewWillDisappear:(BOOL)animated
{
// 文本清空
    [super viewWillDisappear:animated];
    self.phoneTF.text = @"";
    self.nameTF.text = @"";
    self.passwordTF.text = @"";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:_hud];
    [_hud hide:YES];
    
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)saveHandle:(id)sender {
    if (self.phoneTF.text.length == 0 || self.passwordTF.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];
    User *u = [[User alloc]init];
    u.phone = self.phoneTF.text;
    u.password = self.passwordTF.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

5.数据的修改 创建DetailViewController

.h

#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property(nonatomic,strong) User *u;
@end

.m

#import "DetailViewController.h"
#import "PlistDataBase.h"


@interface DetailViewController ()
{
    MBProgressHUD *hub;
}
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *passWordTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
- (IBAction)change:(id)sender;

@end

@implementation DetailViewController

-(void)viewWillAppear:(BOOL)animated
{
    self.phoneTF.text = self.u.phone;
    self.nameTF.text = self.u.name;
    self.passWordTF.text = self.u.password;
}
- (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)change:(id)sender {
    
//    User *newu = [[User alloc]init];
//    newu.ID = self.u.ID;
//    newu.phone = self.u.phone;
//    newu.password = self.u.password;
//    newu.name = self.u.name;
    
    //这句代码实现与上面四句代码等效的效果
    User *newu = [self.u copy];
    
    newu.password = self.passWordTF.text;
    newu.name = self.nameTF.text;
    
    
  PlistDataBase *db = [[PlistDataBase alloc]init];
    BOOL success = [db updateOne:newu];
    hub = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hub];
    hub.removeFromSuperViewOnHide = YES;
    
//    if (success) {
//        hub.labelText = @"更新成功";
//    }else
//    {
//        hub.labelText = @"更新失败";
//    }
    hub.labelText = success ? @"更新成功" : @"更新失败";
    hub.mode = MBProgressHUDModeText;
    [hub show:YES];
    [self performSelector:@selector(back:) withObject:nil afterDelay:2.0];
}
-(void)back:(id)sender

{
    if (hub.isHidden == NO) {
        [hub hide:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

@end

6.完事

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

推荐阅读更多精彩内容

  • //我所经历的大数据平台发展史(三):互联网时代 • 上篇http://www.infoq.com/cn/arti...
    葡萄喃喃呓语阅读 51,180评论 10 200
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,560评论 18 399
  • 月亮出来时 有星星做伴 太阳出来时 我哭了
    皓月万里阅读 153评论 0 0
  • 20岁的我,第一次吃一种叫做土豆泥的食物,那一刻,不论是从口感还是味道,都给了我全新的体验和感受。每次从透明玻璃碗...
    申阳阅读 315评论 0 2