字典中存放的是键值对 可通过键取得值
1.创建不可变字典
1 // 1 f(1) 2 NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil]; 3 NSLog(@"%@",dic); 4 5 // 2 快速创建字典 6 NSDictionary * dic2 = @{@"1":@"one",@"2":@"two",@"3":@"three"}; 7 NSLog(@"%@",dic2);
2.字典中的元素个数
1 NSUInteger count = [dic2 count];
2 NSLog(@"%lu",count);
3.字典中可以存放数组
1 NSArray * arr = @[@"one",@"two",@"three"]; 2 NSDictionary * dic3 = @{@"1":@"one",@"array":arr,@"2":@"two"}; 3 NSLog(@"%@",dic3);
4.字典中取值
1 // 5 从字典中取值 2 NSArray * arr2 = [dic3 objectForKey:@"array"]; 3 NSLog(@"%@",arr2); 4 // 快速取法 5 NSArray * arr3 = dic3[@"array"]; 6 NSLog(@"%@",arr3);
5.可变字典
5.1 可变字典的创建
1 // 创建 2 NSMutableDictionary * muDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2", nil]; 3 4 NSDictionary * dic = @{@"1":@"one",@"2":@"two"}; 5 6 NSMutableDictionary * muDic2 = [[NSMutableDictionary alloc] initWithDictionary:dic]; 7 8 NSLog(@"%@",muDic2);
5.2 向字典中添加元素
1 [muDic2 setObject:@"three" forKey:@"3"]; 2 NSLog(@"%@",muDic2);
5.3 重置字典(set方法)
1 [muDic2 setDictionary:@{@"a":@"one",@"b":@"two"}]; 2 NSLog(@"%@",muDic2);
5.4 删除元素
删除key对应的键值对
1 [muDic2 removeObjectForKey:@"a"];
2 NSLog(@"%@",muDic2);
删除全部
1
2 [muDic2 removeAllObjects];
3 NSLog(@"%@",muDic2);
5.5打印字典中的元素
1 NSArray * arr = [muDic2 allKeys]; 2 // arr存储字典中所有的key 3 NSLog(@"%@",arr); 4 // 用快速枚举的方式打印字典muDic中的值 5 for (NSString * str in arr) { 6 // NSLog(@"%@",[muDic2 objectForKey:str]); 7 NSLog(@"%@",muDic2[str]); 8 }
扩展
- (BOOL)isKindOfClass:(Class)aClass;
判断是否是某种类型
example
[obj isKindOfClass:[NSString class]];
判断obj是否是NSString类型 返回值为BOOL类型
时间: 2024-09-30 14:51:27