一、NSDictionary基本概念
-
NSDictionary的作用类似:通过一个key,就能找到对应的Value
-
NSDictionary是一个不可变的,一旦初始化后,就无法修改
二、NSDictionary的创建
- 方法一:
- 创建一个dictionaryWithObject
- 创建多个dictionaryWithObjects
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"lm" forKey:@"name"];
NSString *name = [dict objectForKey:@"name"];
- 方法二:简单方法
- NSDictionary *dict = @{key1:value1,key2:value2};
NSDictionary *dict = @{@"lm":@"name",@"25":@"age",@"160":@"height"};
三、如何获取
- 方法一:objectForKey
NSString *name = [dict objectForKey:@"name"];
- 方法二:NSLog(@"%@", dict[@"name"]);
四、字典的遍历
-
如何获取字典中key和value的个数,
-
在字典中key称之为键, value称之为值
-
NSLog(@"count = %lu", [dict count]);
-
方法一:for循环【不用】
for (int i = 0; i < dict.count; ++i) {
// 获取字典中所有的key
NSArray *keys = [dict allKeys];
// 取出当前位置对应的key
// NSLog(@"%@", keys[i]);
NSString *key = keys[i];
NSString *value = dict[key];
NSLog(@"key = %@, value = %@", key, value);
}
- 方法二:forin遍历字典【不用】
for (NSString *key in dict) {
// NSLog(@"%@", key);
NSString *value = dict[key];
NSLog(@"key = %@, value = %@", key, value);
}
- 方法三:迭代器遍历enumerateKeysAndObjectsUsingBlock
NSDictionary *dict = @{@"lm":@"name",@"25":@"age",@"160":@"height"};
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"obj:%@, key:%@", obj, key);
}];
五、字典文件读写
- 字典读取writeToFile
- 字典写入dictionaryWithContentsOfFile
[dict writeToFile:@"/Users/jeffrey/Desktop/php.plist" atomically:YES];
NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/jeffrey/Desktop/php.plist"];
六、NSMutableDictionary
- 1.创建一个空的字典
NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
```objc
- 2.如何添加
```objc
[dictM setObject:@"lm" forKey:@"name"];
// 会将传入字典中所有的键值对取出来添加到dictM中
[dictM setValuesForKeysWithDictionary:@{@"age":@"30", @"height":@"1.75"}]
```objc
- 3.如何获取
```objc
NSLog(@"%@", dictM[@"lm"]);
- 4.如何删除
[dictM removeObjectForKey:@"lm"];
- 5.如何修改
- 如果利用setObject方法给同名的key赋值, 那么新值会覆盖旧值
[dictM setObject:@"88" forKey:@"age"];
dictM[@"age"] = @"88";
网友评论