Oc Plist 持久化

来源:互联网 发布:三国战记tas软件 编辑:程序博客网 时间:2024/06/03 05:45

模型属性User.h

#import <Foundation/Foundation.h>@interface User : NSObject<NSCoding>@property (nonatomic,strong)NSString *phone;@property (nonatomic,strong)NSString *password;@property (nonatomic,strong)NSString *name;@end

User.m

#import "User.h"@implementation User//归档操作的两个必须实现的方法//把对象的每个属性做成二进制数据- (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;}@end

数据业务 PlistDataBase.h

#import <Foundation/Foundation.h>@interface PlistDataBase : NSObject<DataBase>///添加- (BOOL)addNew:(id)newObj;///删除- (BOOL)deleteOne:(id)deleteobj;///修改- (BOOL)updataOne:(id)upObj;///获取所有- (id)getAllObjects;///是否重复- (BOOL)objExist:(id)obj;@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<arr.count ; i++)    {        NSData *data = arr[i];        User *u = [NSKeyedUnarchiver unarchiveObjectWithData:data];        if ([u.phone isEqualToString:phone])        {            return i;        }    }    return -1;}@end

展示控制器ShowViewController.m

#import "ShowViewController.h"#import "AddViewController.h"#import "PlistDataBase.h"#import "User.h"#import "DetailViewController.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.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];    }    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 = u.name;    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.xib

屏幕快照 2017-09-03 20.54.44.png

添加控制器AddViewController.h

#import <UIKit/UIKit.h>@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"@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];    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

修改控制器DetailViewController.xib

屏幕快照 2017-09-03 20.57.15.png

修改控制器DetailViewController.h

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

修改控制器DetailViewController.m

#import "DetailViewController.h"#import "PlistDataBase.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.phone = self.passUser.phone;    newU.password = self.pwdTF.text;    newU.name = self.nameTF.text;    PlistDataBase *db = [[PlistDataBase 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

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;}

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 */
原创粉丝点击