代码改变世界

iOS开发备忘录:属性列表文件数据持久化

2014-08-27 16:39  王祖康  阅读(4626)  评论(0编辑  收藏  举报

属性列表文件是一种XML文件,Foundation框架中的数组和字典等都可以于属性列表文件相互转换。

NSArray类常用读写属性列表文件的方法

+arrayWithContentsOfFile:类级构造方法,用于从属性列表文件中读取数据,创建NSArray对象。

-initWithContentsOfFile:实例构造方法,用于从属性列表文件中读取数据,创建NSArray对象。

-writeToFile:atomically:该方法把NSArray对象写入到属性列表文件中,第一个参数是文件名,第二个参数为是否使用辅助文件,如果为YES,则先写入到一个辅助文件,然后辅助文件再重新命名为目标文件,如果为NO,则直接写入到目标文件。

NSDictionary类常用读写属性列表文件的方法:

+dictionaryWithContentsOfFile:类级构造方法,用于从属性列表文件中读取数据,创建NSDictionary对象。

-initWithContentsOfFile:实例构造方法,用于从属性列表文件中读取数据,创建NSDictionary对象。

-writeToFile:atomically:该方法将NSDictionary对象写入到属性列表文件中。

属性列表文件数据持久化具体方法,可参考以下实现方式:

假如在项目中手工创建了一个Contacts.plist文件,并在该文件中添加了几条数据,如下图所示。

当然也可以通过代码直接创建plist文件。

接下来需要做的是将项目资源的Contacts.plist文件中数据复制到沙箱Documents目录下。

//对文件进行预处理,判断在Documents目录下是否存在plist文件,如果不存在则从资源目录下复制一个。
-(void)createEditableCopyOfDatabaseIfNeeded
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *writableDBPath=[self applicationDocumentsDirectoryFile];
    
    BOOL dbexits=[fileManager fileExistsAtPath:writableDBPath];
    if (!dbexits) {
        NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Contacts.plist"];
        
        NSError *error;
        BOOL success=[fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        
        if (!success) {            
            NSAssert1(0,@"错误写入文件:‘%@’",[error localizedDescription]);
        }
    }
}

//获取放置在沙箱Documents目录下的文件的完整路径
-(NSString *)applicationDocumentsDirectoryFile
{
    NSString *documentDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path=[documentDirectory stringByAppendingPathComponent:@"Contacts.plist"];
   
    return path;
}

createEditableCopyOfDatabaseIfNeeded方法中

NSFileManager的copyItemAtPath:toPath:error:方法实现文件复制。

NSAssert1是Foundation框架提供的宏,它在断言失败的情况下抛出异常,类似的还有NSAssert和NSAssert2等。

applicationDocumentsDirectoryFile方法中

stringByAppendingPathComponent:能够在目录后面追加文件名,返回完整的文件路径。

沙箱Documents目录下成功生成plist文件之后,就可以进行增、删、改、查操作了。可参考如下代码:

NSString *path=[self applicationDocumentsDirectoryFile];
    
    //将属性列表文件内容读取到array变量中,也就是获取了属性列表文件中全部的数据集合
    NSMutableArray *array=[[NSMutableArray alloc]initWithContentsOfFile:path];
    
    //向array中添加一条新记录
    NSDictionary *newContact=[NSDictionary dictionaryWithObjects:@[contact.Title,contact.Type] forKeys:@[@"Title",@"Type"]];
    [array addObject:newContact];
    
    //删除array中一条记录
    [array removeObjectAtIndex:0];
    
    //删除array中全部记录
    [array removeAllObjects];
    
    for (NSDictionary* dict in array) {
        //通过for循环,找到需要修改的数据项,进行修改数据
        [dict setValue:@"Test" forKey:@"Title"];
    }
    
    //将array重新写入属性列表文件中
    [array writeToFile:path atomically:YES];

注:完成后,需要选择Product->Clean菜单项清除一些再编译。