美文网首页
Plist文件持久化

Plist文件持久化

作者: 被风吹乱的思念 | 来源:发表于2017-09-20 20:35 被阅读11次

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.完事

相关文章

网友评论

      本文标题:Plist文件持久化

      本文链接:https://www.haomeiwen.com/subject/qfzosxtx.html