NSMutableDictionary基础-创建、插入、删除、遍历、枚举

代码:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //创建空可变字典
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        //创建可变字典并赋值
        NSMutableDictionary *dic1=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Jay",@"name",@"22",@"age",@"Female",@"Sex",nil];
        //可变字典赋值
        [dic setDictionary:dic1];
        //字典中插入键值对
        NSDictionary *dic2=[NSDictionary dictionaryWithObject:@"166" forKey:@"height"];
        [dic1 addEntriesFromDictionary:dic2];
        [dic1 setValue:@"66" forKey:@"width"];
        NSLog(@"%@",dic1);
        //删除字典中key对应的值
        [dic1 removeObjectForKey:@"name"];
        NSArray *arr1=[NSArray arrayWithObjects:@"height",@"Sex",nil];
        [dic1 removeObjectsForKeys:arr1];
        NSLog(@"%@",dic1);
        //删除字典中全部数据
        [dic1 removeAllObjects];
        //遍历
        NSMutableDictionary *dic3=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Jay",@"name",@"22",@"age",@"Female",@"Sex",nil];
            //1.找到所有key,2计算key个数,3通过key的数组找到对应key值
        NSArray *keys=[dic3 allKeys];
        NSInteger count=[dic3 count];
        for (int i=0;i<count;i++) {
            id key=[keys objectAtIndex:i];
            NSLog(@"%@",[dic3 objectForKey:key]);
        }
        //快速枚举
        for (id key in dic3) {
            id obj=[dic3 objectForKey:key];
            NSLog(@"%@=%@",key,obj);
        }
        //枚举对象(通过枚举对象进行枚举)
            //1.将字典里的key放到枚举对象中,用于遍历/枚举
        NSEnumerator *keyEnum=[dic3 keyEnumerator];
        id key=[keyEnum nextObject];
        while(key){
            id obj=[dic3 objectForKey:key];
            NSLog(@"%@",obj);
            key=[keyEnum nextObject];
        }
    }
    return 0;
}

 

posted @ 2016-01-08 10:28  零点五  阅读(2061)  评论(0编辑  收藏  举报