- (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);
}
iOS 中plist中的对象的读写操作
最新推荐文章于 2020-04-28 20:20:55 发布