可变字典 添加 删除 遍历

#import <Foundation/Foundation.h>

 int main(int argc, const char * argv[]) {

    @autoreleasepool {

        //可变字典

        NSMutableDictionary *nud=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"JAY",@"name",@"22",@"age",@"f",@"gender", nil];

        NSLog(@"%@",nud);

        //添加

//        NSDictionary *die=[NSDictionary dictionaryWithObject:@"6" forKey:@"hehe"];

//        [nud addEntriesFromDictionary:die];

//        NSLog(@"%@",nud);

        //直接添加

//        [nud setValue:@"66" forKey:@"ent"];

//        NSLog(@"%@",nud);

        //创建字典  像空字典赋值

        NSMutableDictionary *str=[NSMutableDictionary dictionary];

        //讲字典str设置与字典nud对象相同

        [str setDictionary:nud];

        //将字典中对应的k的值删除

//        [str removeObjectForKey:@"gender"];

//        NSLog(@"%@",str);

        //利用数组删除

//        NSArray *arr=[NSArray arrayWithObjects:@"age",@"name", nil];

//        [str removeObjectsForKeys:arr];

//        NSLog(@"%@",str);

        //全部删除

//        [str removeAllObjects];

//         NSLog(@"%@",str);

        //遍历

        //想找到所有k值,计算k的个数,用以循环遍历条件:通过k的数组找到对应的k值

//        NSArray *arr1=[str allKeys];

//        NSInteger count=[arr1 count];

//        for(int i=0;i<str.count;i++){

//            id key=[arr1 objectAtIndex:i];

//            NSLog(@"%@",key);

//        

//        }

        //快速枚举

//        for(id key in str){

//        

//            id obj=[str objectForKey:key];

//            NSLog(@"%@",obj);

//        }

        //通过枚举对像进行枚举

        //讲字典里的k转化成枚举对象,用于遍历

        NSEnumerator *kent=[str keyEnumerator];

         //进入枚举对象取出枚举对象的第一个元素,赋值给key

        id ker=[kent nextObject];

        while (ker) {

            id  obj1=[str objectForKey:ker];

            NSLog(@"%@",obj1);

          //向下移动一位取出第二个元素

            ker=[kent nextObject];

        } 

    }

    return 0;

}

原文地址:https://www.cnblogs.com/j-h-t-123-n/p/5115712.html