[关闭]
@fiy-fish 2015-07-15T20:17:51.000000Z 字数 2043 阅读 1375

day05-04-字典

Objective-c


  1. // main.m
  2. // day05-04-字典
  3. //
  4. // Created by Aaron on 15/7/7.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. //字典
  9. //键值对
  10. //key----value
  11. //键值对成对出现
  12. //一一对应
  13. //哈希
  14. //key必须是唯一的
  15. //value可以是多个
  16. //里面存储的都只能是对象
  17. //NSDictionary
  18. //NSMutableDictionary
  19. #if 0
  20. int main(int argc, const char * argv[]) {
  21. @autoreleasepool {
  22. NSDictionary *dic = [[NSDictionary alloc] init];
  23. //用键值对来初始化字典
  24. //注意:值在前,键在后,成对出现
  25. //没有顺序
  26. NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@1,@"one",@2,@"two",@3,@"three", nil];
  27. NSLog(@"%@",dic1);
  28. NSArray *valueArray = @[@1,@2,@3,@4];
  29. NSArray *keyArray = @[@"one",@"three",@"four",@"two"];
  30. //用键值对数组来初始化字典
  31. NSDictionary *dic2 = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
  32. NSLog(@"%@",dic2);
  33. NSDictionary *dic3 = [[NSDictionary alloc] initWithDictionary:dic2];
  34. //NSDictionary *dic4 = [NSDictionary dic]
  35. //类方法创建字典
  36. //2.0新特性
  37. //@{key:value,key:value....}
  38. }
  39. return 0;
  40. }
  41. #endif
  42. #if 0
  43. int main()
  44. {
  45. //常用的方法
  46. NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@1,@"three",@2,@"two", nil];
  47. //获取键值对的个数
  48. NSInteger count = [dic count];
  49. NSLog(@"%ld",count);
  50. //获取key对应的value
  51. id obj = [dic objectForKey:@"one"];
  52. NSLog(@"%@",obj);
  53. //获取值对应的键
  54. NSArray *keys = [dic allKeysForObject:@1];
  55. NSLog(@"%@",keys);
  56. //获取所有的键
  57. NSArray *allKeys = [dic allKeys];
  58. NSLog(@"%@",allKeys);
  59. //获取所有的值
  60. NSArray *objs = [dic allValues];
  61. NSLog(@"%@",objs);
  62. }
  63. #endif
  64. //字典的遍历
  65. #if 0
  66. int main()
  67. {
  68. NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@1,@"three",@2,@"two", nil];
  69. //for in快速遍历
  70. for(id obj in dic)
  71. {
  72. //遍历出来的是key
  73. NSLog(@"%@",obj);
  74. }
  75. NSEnumerator *enumerator = [dic keyEnumerator];
  76. enumerator = [dic objectEnumerator];
  77. id obj = nil;
  78. while(obj = [enumerator nextObject])
  79. {
  80. NSLog(@"%@",obj);
  81. }
  82. }
  83. #endif
  84. int main()
  85. {
  86. //可变字典
  87. NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  88. //增删改
  89. //添加键值对其实是设置一对键值对
  90. [dic setObject:@10 forKey:@"ten"];
  91. NSLog(@"%@",dic);
  92. //从另外一个字典里将键值对添加到当前字典
  93. [dic addEntriesFromDictionary:@{@"two":@2}];
  94. NSLog(@"%@",dic);
  95. //修改
  96. [dic setObject:@22 forKey:@"two"];
  97. NSLog(@"%@",dic);
  98. //删除
  99. //删掉key所对应的键值对
  100. // [dic removeObjectForKey:@"two"];
  101. // [dic removeObjectsForKeys:@[@"ten",@"two"]];
  102. [dic removeAllObjects];
  103. [dic setDictionary:@{}];
  104. NSLog(@"%@",dic);
  105. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注