字典中的一些操作
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableDictionary *mudic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Jay",@"name",@"22",@"age",@"F",@"gender",nil];
// NSLog(@"%@",mudic);
NSDictionary *dic=[NSDictionary dictionaryWithObject:@"166" forKey:@"height"];
//向字典内添加key-value
[mudic addEntriesFromDictionary:dic];
[mudic setValue:@"66" forKey:@"weight"];
// NSLog(@"%@",mudic);
NSMutableDictionary *newdic=[NSMutableDictionary dictionary];
//将字典newdic设置与字典mudic对象相同
[newdic setDictionary:mudic];
//将字典中对应key的值删除
[newdic removeObjectForKey:@"weight"];
NSArray *keys=[NSArray arrayWithObjects:@"height",@"gender",nil];
[newdic removeObjectsForKeys:keys];
[newdic removeAllObjects];
[newdic setDictionary:mudic];
//遍历
//1.先找到所有key;2.计算key的个数,用于循环遍历条件3.通过key的数组找到对应key的值
NSArray *keyss=[newdic allKeys];
for (int i=0; i<newdic.count; i++) {
id key=[keyss objectAtIndex:i];
NSLog(@"%@",[newdic objectForKey:key]);
}
NSLog(@"✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨");
//2.快速枚举:for in 语句
for (id key in newdic) {
id obj=[newdic objectForKey:key];
NSLog(@"%@",obj);
}
NSLog(@"🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞");
//3.通过枚举对象进行枚举
//1.将字典里的key转成枚举对象,用于遍历/枚举
NSEnumerator *keyenum=[newdic keyEnumerator];
//2.进入枚举对象取出枚举对象的第一个元素,赋值给key
id key=[keyenum nextObject];
//3.循环key值,取到空时暂停循环
while (key) {
//4.通过key取value
id obj=[newdic objectForKey:key];
NSLog(@"%@",obj);
//5.向下移动一位取出第二个元素
key=[keyenum nextObject];
}
//NSLog(@"%@",newdic);
}
return 0;
}