OC NSDictionary

OC NSDictionary


NSDictionary初始化

NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2", nil];

NSDictionary * dict2 = [NSDictionary dictionaryWithObjects:@[@"value1",@"value2"] forKeys:@[@"key1",@"key2"]];

NSDictionary * dict3 = @{@"key1":@"value1",@"key2":@"value2”};//字面量形式

通过key值获取value值

[dict3 objectForKey:@(2)] //key值可以是任意对象
[dict3 valueForKey:@"key2"] //key值只能是NSString
dict3[@"key2"]  //字面量形式,建议使用

获取字典中所有的key值

[dict3 allKeys]

获取字典中所有的value值

[dict3 allValues]

一种value找出所有对应的key值

[dict allKeysForObject:@"b"]

key的枚举器

NSEnumerator *enumerator = [dict keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
     NSLog(@"%@",key);
}

block的枚举

[dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
      NSLog(@"key = %@ value = %@",key,obj);
}];

NSMutableDictionary

初始化

[NSMutableDictionary dictionary]

给字典添加或修改内容

当字典里没有key值的时候,是添加。
当字典里有key值的时候,是修改。
[dict setObject:@"value2" forKey:@"key2"];
dict[@"key1"] = @"value1";//字面量写法

删除字典中的元素

[dict removeObjectForKey:@"key1"];
[dict removeObjectsForKeys:@[@"key1",@"key2"]];
[dict removeAllObjects];
posted @ 2016-05-16 08:37  旭宝爱吃鱼  阅读(291)  评论(0编辑  收藏  举报