本文主要讲解的是不可变字典NSDictionary可变字典NSMutableDictionary字典NSDictionary和Json转换详细使用方式包括类型和值之间的转换
文章是博主原创,转载请标明出处http://blog.csdn.net/werctzzz/article/details/71713293
首先来看看不可变的字典
#pragma mark NSDictionary 不可变字典 // NSDictionary用于键值映射 // 1.字典的初始化(常见的几种方式) NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"@123" forKey:@"key1"]; NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2" ,nil]; NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic1]; NSDictionary *dic4 = @{@"key1": @"value1",@"key2": @"value2"}; NSString * path = @"路径"; NSDictionary *dic5 = [NSDictionary dictionaryWithContentsOfFile:path]; // 2.字典的常用操作 // key - value ;输入的时候 [值 - 键] NSLog(@"%@",dic1); //输出的时候 为 [键 - 值]; //2.值得获取和遍历 // 2.1 NSArray *key = [dic1 allKeys]; NSLog(@"%@", key); // 2.2获取所有value值 NSArray *value = [dic1 allValues]; NSLog(@"%@", value); // 2.3通过key查询value NSString *name = [dic1 objectForKeyedSubscript:@"name"]; NSLog(@"%@", name);//查找name key 对应的 value 值 // 2.4根据allkeys数组获取字典中所有的key - value对 //间接遍历 for (NSString *key1 in key) { NSString *value = [dic1 objectForKey:key1]; NSLog(@"%@ = %@:", key1 ,value); } //直接遍历 for (NSString *key1 in dic1) { NSString *value = [dic1 objectForKey:key1]; NSLog(@"%@ = %@", key1 ,value); }
然后是可变字典的方法
#pragma mark NSMutableDictionary 可变字典 //NSMutableDictionary //1.创建初始化 NSMutableDictionary * mdic = [NSMutableDictionary dictionaryWithDictionary:dic2]; //通过不可变的dic1传来的值,创建可变的字典 //2.添加键值对 和 设定 // 2.1添加一个指定键值对 [mdic setValue:@"wu dang" forKey:@"attribute"]; NSLog(@"%@", mdic); // 2.2像字典中添加整个字典对象 [mdic addEntriesFromDictionary:dic1]; // 2.3把字典内容设置与指定字典的内容相同 [mdic setDictionary:dic1]; //3.修改key 对应的value [mdic setValue:@"shan jia" forKey:@"hobby"]; NSLog(@"%@", mdic); //4.删除键值对 // 4.1删除制定键值对 [mdic removeObjectForKey:@"sex"]; NSLog(@"%@", dic2); // 4.2删除在数组中包含的指定key的对应的值 NSArray *array = @[@"key1",@"key2",@"key3"]; [mdic removeObjectsForKeys:array]; // 4.3删除字典中的所有对象 [mdic removeAllObjects];
最后就是常用的字典和json互相转换的方法,很实用~
#pragma mark NSDictionary 和 json 的互相转化 // 1.字典转成json NSDictionary *jsondic = [NSDictionary dictionaryWithObjectsAndKeys: @"zhang san",@"name", @"men",@"sex", @"playgame",@"hobby", @"347",@"age",nil]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsondic options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; // 2.json转成字典 NSData *data = [jsonString dataUsingEncoding:NSASCIIStringEncoding]; NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
作者:werctzzz 发表于2017/5/12 11:27:47 原文链接
阅读:229 评论:0 查看评论