[数据存储]属性列表plist

本文介绍了Plist文件(属性列表文件)的基本概念及其在iOS开发中的应用。提供了使用Objective-C进行Plist文件读取与写入的具体实现方法,并附带了错误处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/detail/wanghuafeng123456/5891439

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值