您的位置:首页 > 移动开发 > IOS开发

实战ios Plist 读 写操作及修改 删除 排序

2013-11-12 17:46 337 查看
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 <Foundation/Foundation.h>

@interface SaveStudentMessagePlist :
NSObject
-(id)initWithStudentName:(NSString *)name Studentage:(NSString *)age StudentNumber:(NSString * )numerb StudentNation:(NSString
*)nation;
@end

//////////////////////////////////////////在.m文件里实现方法///////////////////////////////////////////////////////////////////

-(id)initWithStudentName:(NSString *)name Studentage:(NSString *)age StudentNumber:(NSString * )numerb StudentNation:(NSString
*)nation
{
    //我们把学生的信息保存在可变数组里
    NSMutableArray *studentMessageArray = [[NSMutableArray  alloc]initWithObjects:name,age,numerb,nation,nil];
    if (self = [superinit])
    {
        [self createStudentMessagePlist:studentMessageArraykey:numerb];  // 因为学生的学号是唯一的作为词典的key值
    }
    return self;
    
}

// 创建plist 写入操作
-(void)createStudentMessagePlist:(NSMutableArray *)studentMessageArray key:(NSString *)studentNumebr
{
    
    //沙盒路径
    NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory = [paths
objectAtIndex:0];
    // plist 路径
    NSString *plistPath    = [documentsDirectorystringByAppendingPathComponent:@"student.plist"];
    NSFileManager *fileManager = [[NSFileManager  alloc]init];
     // 下面这几步很重要  通过文件管理器 来判读plist 文件是否存在! 如果不存在 我们就通过  [fileManager createFileAtPath:plistPath contents:nil attributes:nil创建一个plist
并检测是否成功失败!存在后写入词典
如何存在plist 我们就 在 studentMessageDic 可变词典里保存在来色数据这样可以避免数据被覆盖问题

    if(![fileManager fileExistsAtPath:plistPath])
    {
        if(![fileManager createFileAtPath:plistPathcontents: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:plistPathatomically:YES];
        
    }
    
    
}

现在让我们调用方法吧! 打印路径plistPath 我们在沙盒里就会找到你的文件了如下图
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    

   
    if (![studentNumberTextField.tex   tisEqualToString:@"" ])

    {
        SaveStudentMessagePlist *save = [[SaveStudentMessagePlist  alloc]initWithStudentName:studentNameTextField.textStudentage:studentAgeTextFIeld.textStudentNumber:studentNumberTextField.textStudentNation:studentnationTextField.text];

    }
   
    
}

三 对plist 经行读操作

我创建了一个只定义的tableview 来显示学生的信息

-(void)readStudentMessageFromPlist
{
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager  defaultManager];
    
    NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *documentation = [path   objectAtIndex:0];
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[documentationstringByExpandingTildeInPath]];

    NSString *studentPlistPath = [documentation   stringByAppendingPathComponent:@"student.plist"];
    
    _studentMessageDic = [[NSMutableDictionary    alloc]initWithContentsOfFile:studentPlistPath];
    
    NSLog(@"%d", [_studentMessageDicallKeys].count);
    
}

然后在tableview上显示

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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  plist