[数据存储]属性列表plist

来源:互联网 发布:开淘宝店卖什么最赚钱 编辑:程序博客网 时间:2024/05/22 01:47

Plist 文件全称是Property List,即属性列表文件,一般用来做一些配置信息的存储,存储格式是xml。

既然是文件的话,我们当然可以直接以读写文件的方式来做,但是apple还是给我们提供了一套接口来用,所以还是尽量用提供的接口吧。

读:

- (NSArray *)loadPlistDataWithPath:(NSString *)path{    NSError *error = nil;    NSPropertyListFormat format;    NSArray *plistDataArray = (NSArray *)[NSPropertyListSerialization                                          propertyListWithData:[NSData dataWithContentsOfFile:self.plistPath]                                          options:NSPropertyListMutableContainersAndLeaves                                          format:&format                                          error:&error];    if (!plistDataArray) {        NSLog(@"error: %@\nformat: %d", error, format);    }    return plistDataArray;}

当然你返回的是NSDictionary还是NSArray要你自己去判断或者转换类型。

写:

        NSMutableArray *updatedArray = [NSMutableArray arrayWithArray:self.cityArray];        [updatedArray insertObject:self.textField.text atIndex:0];        NSError *error = nil;        NSData *data = [NSPropertyListSerialization dataWithPropertyList:updatedArray                                                                  format:NSPropertyListXMLFormat_v1_0                                                                 options:NSPropertyListMutableContainersAndLeaves                                                                   error:&error];        if (data && [data writeToFile:self.plistPath atomically:YES]) {            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"plist" message:@"Save data success!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];            [alert show];        } else {            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"plist" message:@"Save data failed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];            [alert show];            NSLog(@"error: %@", error);        }

就是这么简单。ok,Done。

所有数据存储的例子:http://download.csdn.net/detail/wanghuafeng123456/5891439