iOS 中plist中的对象的读写操作

本文介绍了一个使用Objective-C编写的示例程序,演示了如何从Plist文件中读取数据并将其输出,同时也展示了如何创建新的字典对象并将它们写回到Plist文件中。该示例适用于学习Objective-C中Plist文件的基本操作。

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

- (IBAction)readPlist:(id)sender
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Person" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
   // NSLog(@"%@", data);//直接打印数据。
//    NSLog(@"\n指定对象名获取对象---:%@", [data objectForKey:@"person_1"]);
//    NSString *name = [[data objectForKey:@"person_1"] objectForKey:@"name"];
//    NSLog(@"\n指定对象名获取对象属性:person_1.name---:%@", name);
    
    
    //遍历字典
    for (NSString *key in data)
    {
        //NSLog(@"\nkey:%@   value:%@", key,[data objectForKey:key]);
        
        //输出对象的属性值
        NSNumber *age  =(NSNumber*) [[data objectForKey:key] objectForKey:@"age"];
        
        NSString *name = [[data objectForKey:key] objectForKey:@"name"];
        
        NSString * sex = [[data objectForKey:key] objectForKey:@"sex"];
        
        NSLog(@"\n name:%@   age:%@   sex:%@", name,age,sex);
        
        
    }

}

- (IBAction)writePlist:(id)sender
{
    
    NSString *name_key = @"name";
    NSString *age_key = @"age";
    NSString *sex_key = @"sex";
    
    NSString *name = @"越敏";
    NSNumber *age = [NSNumber numberWithInteger:123];
    NSString *sex = @"woman";
    
    NSDictionary *tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
                               name,name_key,
                               age,age_key,
                               sex,sex_key,
                               nil];
    
   // NSLog(@"09090----:%@",tempDict);
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Person" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
   // NSLog(@"%@", data);
    
    //添加一项内容
    [data setObject:tempDict forKey:@"person_3"];
    
    
    //获取应用程序沙盒的Documents目录
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename=[plistPath1 stringByAppendingPathComponent:@"Person.plist"];
    //输入写入
    [data writeToFile:filename atomically:YES];
    
    //打印;输出结果
    NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
    NSLog(@"%@", data1);
    
    

    
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值