Foundaton框架-->NSDictionary字典

2016-10-22  本文已影响9人  爱貌貌Manners

一、NSDictionary基本概念

二、NSDictionary的创建

NSDictionary *dict = [NSDictionary dictionaryWithObject:@"lm" forKey:@"name"];
NSString *name = [dict objectForKey:@"name"];
NSDictionary *dict = @{@"lm":@"name",@"25":@"age",@"160":@"height"};

三、如何获取

NSString *name = [dict objectForKey:@"name"];

四、字典的遍历

 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);
    }
for (NSString *key in dict) {
//        NSLog(@"%@", key);
        NSString *value = dict[key];
        NSLog(@"key = %@, value = %@", key, value);
    }
    NSDictionary *dict = @{@"lm":@"name",@"25":@"age",@"160":@"height"};
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSLog(@"obj:%@, key:%@", obj, key);
    }];

五、字典文件读写

[dict writeToFile:@"/Users/jeffrey/Desktop/php.plist" atomically:YES];
NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/jeffrey/Desktop/php.plist"];

六、NSMutableDictionary

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"]);
[dictM removeObjectForKey:@"lm"];
[dictM setObject:@"88" forKey:@"age"];
     dictM[@"age"] = @"88";
上一篇下一篇

猜你喜欢

热点阅读