iOS学习笔记—— 数据持久化(Plist)

这篇博客详细介绍了iOS中数据持久化的一种方式——Plist,包括如何读取全部数据和插入新数据的操作步骤,是iOS开发者学习数据存储的重要参考资料。

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

1、读取全部数据

- (NSMutableArray *) loadAllData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       // 从属性列表读取数据

    for (NSDictionary *dict in dataArray) {
        LLInfo *info = [LLInfo infoMake:[dict objectForKey:@"name"] :[dict objectForKey:@"age"]];
        [ans addObject:info];
    }
    return ans;
}


2、插入数据

- (void) insertInfo:(LLInfo *)data
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[data.name, data.age] forKeys:@[@"name", @"age"]];
    [dataArray addObject:dict];
    [dataArray writeToFile:path atomically:YES];    
}


3、删除数据

- (void) deleteInfo:(LLInfo *)data
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       // 从属性列表读取数据
    
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: data.name] == 0) {
            [dataArray removeObject:dict];
            [dataArray writeToFile:path atomically:YES];
            break;
        }
    }
}

4、交换数据位置

- (void) exchangeInfo: (LLInfo *) from : (LLInfo *) to
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];       // 从属性列表读取数据
    int i = -1, j = -1;
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: from.name] == 0) {
            i = [dataArray indexOfObject:dict];
        }
        if ([[dict objectForKey:@"name"] compare: to.name] == 0) {
            j = [dataArray indexOfObject:dict];
        }
        if (i != -1 && j != -1) {
            break;
        }
    }
    [dataArray exchangeObjectAtIndex:i withObjectAtIndex:j];
    [dataArray writeToFile:path atomically:YES];
}

5、修改数据

- (void) modifyInfo: (LLInfo *) data : (LLInfo *) newData
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
    
    for (NSDictionary *dict in dataArray) {
        if ([[dict objectForKey:@"name"] compare: data.name] == 0) {
            [dict setValue: newData.name forKey:@"name"];
            [dict setValue: newData.age forKey:@"age"];
            [dataArray writeToFile:path atomically:YES];
            break;
        }
    }
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值