iOS使用读写plist文件方式对数据进行增删改查

pist 最为持久化保存的一种方式!本身plist文件是xml ,对于小数量数据可以采用plis 的方法!这样更高效!废话不多说了!进入正题吧!如果是一个新手用plist的话一定会遇到各种问题!我当时就是这样走过来的!也是做个总结吧!

功能介绍:保存学生的基本信息:

一.
在故事板上拖拽几个控件吧如下图用来输入学生的信息
并在ViewController.h 里关联相应的控件!
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *studentNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *studentNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *studentnationTextField;
@property (weak, nonatomic)IBOutletUITextField *studentAgeTextFIeld;

二.创建一个保存学生信息的类 SaveStudentMessagePlist 并继承 NSObject
SaveStudentMessagePlist.h 文件里创建一个初始化的函数

import

pragma mark - Table view data source

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {

    // Return the number of sections.
    return 1;
    }

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {

    // Return the number of rows in the section.
    return [[_studentMessageDicallKeys]count];
    }

  • (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

    NSString *keyValue = [[_studentMessageDic allKeys]objectAtIndex:indexPath.row];
    NSArray *studenMessageArr = [_studentMessageDic objectForKey:keyValue];

    static NSString *CellIdentifier =@”Cell”;
    StudentCell cell = (StudentCell )[tableView dequeueReusableCellWithIdentifier:@”StudentCell”];
    if (cell == nil)
    {
    if (cell == nil)
    {
    cell = [[StudentCellalloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    }

    cell.name.text = [studenMessageArrobjectAtIndex:0];
    cell.age.text = [studenMessageArrobjectAtIndex:1];
    cell.number.text = [studenMessageArrobjectAtIndex:2];
    cell.national.text = [studenMessageArrobjectAtIndex:3];
    return cell;
    }

当我们输入多个学生信息的时候我们会发现!数据根本不是按顺序显示的!(⊙_⊙)? 我们在plist表里明明看的是顺序写入的,但是显示的时候确是随机的!这时候应该想到的是排序! 好吧我把key 经行排序!

其实我们把红色 key 的那段函数改成下面的就可以了
NSArray *keyArray = [[_studentMessageDic allKeys]sortedArrayUsingSelector:@selector(compare:)]; //经行排序

NSString *keyValue = [ keyArray objectAtIndex:indexPath.row];

眼见为实 如图

四 这时候如果一个学生转学了!我们就要删除他的信息
这时候我们需要把以前的代码小改变下
我们把排序放在读取plist函数(-(void)readStudentMessageFromPlist)里更好!并设置为全局变量

_keyArray = [[_studentMessageDic   allKeys]sortedArrayUsingSelector:@selector(compare:)];

并把路径也改完全局的
在tableview的委托里进行删除
-(void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath
{
[self.tableViewbeg inUpdates];

if (editingStyle ==UITableViewCellEditingStyleDelete)
{

    [_studentMessageDic   removeObjectForKey:[_keyArray    objectAtIndex:indexPath.row]];
    [_studentMessageDic  writeToFile:_studentPlistPath    atomically:YES];

    [self.tableView    deleteRowsAtIndexPaths:[NSMutableArray     arrayWithObject:  indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic];


}
[self.tableView    endUpdates];

}

现在就只有小花了

看下效果吧:
五 这时候一位老师输入一个新同学叫小米!但是不小心学号输入错了输入了小花的学号!
发现小花的信息出被替换了!这时候程序员又要做个判读了!

我在存入前遍历了下plist 如果存在就不进行写入操作 ,这样可以避免保存相同的数据!
// 创建plist
-(void)createStudentMessagePlist:(NSMutableArray )studentMessageArray key:(NSString )studentNumebr
{

BOOL isOrSava = YES;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths  objectAtIndex:0];
NSString *plistPath = [documentsDirectory   stringByAppendingPathComponent:@"student.plist"];
NSFileManager *fileManager = [[NSFileManageralloc]init];

NSMutableDictionary *studentMessageDic = [NSMutableDictionarydictionaryWithContentsOfFile:plistPath];


if ([studentMessageDic count] >= 1)
{

    //遍历key
    for (id objin [studentMessageDic    allKeys])
    {
        NSString *objstring = obj;

        if ([[studentMessageArray objectAtIndex:2] isEqualToString:objstring])
        {
            isOrSava = NO; // 如果存在设置为NO
            NSLog(@"学号以存在");
            break;
        }
    }

if (isOrSava == YES)
{
    if(![fileManager fileExistsAtPath:plistPath])
    {
        if(![fileManager createFileAtPath:plistPath contents:nilattributes:nil])
        {
            NSLog(@"create file error");
        }
        else
        {

            NSDictionary* studentMessageDic = [NSDictionary  dictionaryWithObjectsAndKeys:studentMessageArray,studentNumebr ,nil];
            [studentMessageDic writeToFile:plistPathatomically:YES];

        }
    }
    else
    {

        NSMutableDictionary *studentMessageDic= [[NSMutableDictionary    alloc]initWithContentsOfFile:plistPath];
        [studentMessageDic setObject:studentMessageArray forKey:studentNumebr ];
        [studentMessageDic writeToFile:plistPath    atomically:YES];

    }


}


}else
{

    if(![fileManager fileExistsAtPath:plistPath])
    {
        if(![fileManager createFileAtPath:plistPath contents:nilattributes:nil])
        {
            NSLog(@"create file error");
        }
        else
        {

            NSDictionary* studentMessageDic = [NSDictionarydictionaryWithObjectsAndKeys:studentMessageArray,studentNumebr ,nil];
            [studentMessageDic writeToFile:plistPathatomically:YES];

        }
    }
    else
    {

        NSMutableDictionary *studentMessageDic= [[NSMutableDictionaryalloc]initWithContentsOfFile:plistPath];
        [studentMessageDic   setObject:  studentMessageArray    forKey:studentNumebr ];
        [studentMessageDic writeToFile:plistPathatomically:YES];

    }



}

}

六 又过了几天 老师找到程序员说!我要可以修改学生的年龄!可是当时的需求没有要求呀!找知道可以修改不如用数据库 ,coredata ,可是这是一个很懒的程序员!我想直接对plist 经行修改吧!
点击cell 显示当前学生的年龄 改成你想改的年龄 然后返回首页 改成15 了 很懒的程序员只是加了几行代码

用到 atIndexedSubscript 插入函数 把这个学习的年龄修改后在重新写入了plist
- (IBAction)SaveMessage:(id)sender
{

[_insterstudenMessage   setObject:_ageTextField.text atIndexedSubscript:1];

NSMutableDictionary *studenDic = [[NSMutableDictionary  alloc]init];

[studenDic setValue:_insterstudenMessageforKey:[_insterstudenMessage  objectAtIndex:2]];

[studenDic  writeToFile :_path   atomically:YES];

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值