版权声明:本文为博主原创,如需转载请注明出处。
字典是以键值对的形式来存储数据 key value
1 NSDictionary 字典
1.1 创建字典,不可变的
1 | NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:@"xiaozhe",@"name", nil]; |
1 | 2016-08-14 14:44:17.460 07-字典类[2325:547877] dic { |
1.2 快捷创建方式
1 | NSDictionary * dic2 = @{ @"one":@"1",@"two":@"2"}; |
1 | 2016-08-14 14:44:17.461 07-字典类[2325:547877] dic2 { |
1.3 字典中可以存任意数据类型
字典的顺序不是自然顺序
1 | NSArray * array = @[@"one",@"two"]; |
1 | 016-08-14 14:44:17.461 07-字典类[2325:547877] dic3 { |
1.4 获得字典的长度
1 | NSLog(@"count %ld",dic3.count); |
1.5 从字典中取值
1 | NSString * str = [dic3 objectForKey:@"one"]; |
1.6 遍历
取出所有的key值
1 | NSArray * allkeys = [dic3 allKeys]; |
枚举器
1 | NSEnumerator * enumerator = [dic3 objectEnumerator]; |
2 NSMutableDictionary 可变字典
2.1 创建一个可变长度字典
1 | NSMutableDictionary * muDic = [[NSMutableDictionary alloc] initWithCapacity:0]; |
2.2 向字典中存储数据
1 | [muDic setObject:@"1" forKey:@"one"]; |
2.3 删除
1 | [muDic removeObjectForKey:@"one"]; |
2.4 全部删除
1 | [muDic removeAllObjects]; |
给一个 Student 类
1 | @interface Student : NSObject |
1 |
|
1 | Student * stu1 = [[Student alloc] initWithName:@"xiaoher" andAge:20]; |
2.5 使用for循环遍历字典
1 | NSArray * allkeys = [muDic allKeys]; |
2.6 使用枚举器
1 | NSEnumerator * enumerator = [muDic objectEnumerator]; |
新博客文章地址:NSDictionary字典创建,获取,遍历,可变字典的删除
CSDN文章地址:NSDictionary字典创建,获取,遍历,可变字典的删除