《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <五> NSDicionary + NSMutableDictionary...

本文介绍了Objective-C中字典的基本操作,包括初始化、增删查改等,并演示了如何使用不同方法创建和操作字典,如NSDictionary和NSMutableDictionary的使用技巧。

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

 

 1 int main(int argc, const char * argv[]) {
 2     @autoreleasepool {
 3         //字典, 存储的内存不是连续的 用key和value进行对应(键值)
 4         //kvc 键值编码
 5         NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];
 6         NSLog(@"%@",dic);//以上的方法是不常用的
 7         //注意两个参数是数组
 8         //NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:<#(NSArray *)#> forKeys:<#(NSArray *)#>]
 9         //所以还是要先创建两个数组
10         NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d", nil];
11         NSArray *array2 = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil];
12         NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:array1 forKeys:array2];
13         NSLog(@"%@",dic2);
14         //
15         NSDictionary *dic3 = @{@"m":@"9",@"n":@"8"};
16         NSLog(@"%@",dic3);
17         //输出字典的长度
18         int count = (int)[dic3 count];
19         NSLog(@"%d",count);
20         //通过键 获得 值
21         NSString *str = [dic3 valueForKey:@"m"];//或者[dic3 objectForKey:@"m"]
22         NSLog(@"%@",str);
23         //获取所有键值中的键和值
24         NSArray *allValue = [dic3 allValues];
25         NSArray *allKey = [dic3 allKeys];
26         //通过多个键找值,因为是多个,当然返回的是数组
27         NSArray *array = [dic2 objectsForKeys:[NSArray arrayWithObjects:@"2",@"3",@"9", nil] notFoundMarker:@"not found"];
28         NSLog(@"%@",array);
29         //遍历字典,数组通过下标遍历,字典当然通过key来遍历
30         for (NSString *key in dic2) {
31             NSLog(@"%@ = %@",key,[dic2 objectForKey:key]);
32         }
33         //使用针对字典的枚举器
34         NSEnumerator *en = [dic2 keyEnumerator];
35         id key = nil;
36         while (key = [en nextObject]) {
37             NSLog(@"key - %@",key);
38         }
39         //还有一个block方法,用法都是一样的
40         /*
41         [dic2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
42             
43         }];*/
44     }
45     return 0;
46 }

 

 
 1 int main(int argc, const char * argv[]) {
 2     @autoreleasepool {
 3         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
 4         //添加键值对,直接添加就可以了
 5         [dict setObject:@"1" forKey:@"a"];
 6         [dict setObject:@"2" forKey:@"b"];
 7         [dict setObject:@"3" forKey:@"c"];
 8         NSLog(@"%@",dict);
 9         //删除键值对
10         [dict removeObjectForKey:@"a"];
11         NSLog(@"%@",dict);
12         //还可以通过传入数组对象,对应删除数组元素对应的所有键
13         [dict removeObjectsForKeys:[NSArray arrayWithObjects:@"a",@"c", nil]];
14         NSLog(@"%@",dict);
15     }
16     return 0;
17 }

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值