OC中字典NSDictionary和可变字典NSMutableDictionary<代码演示>

来源:互联网 发布:6120ci软件 编辑:程序博客网 时间:2024/04/27 20:49
不可变字典    
//字典(NSDictionary)<相当于Java中的Map集合:以键值对Key--》Value>和 可变字典(NSMutableDictioary)<>
        //NSDictionary 字典  NSMutableDictionary(可变字典)
        //相当于Java中的Map集合 是以 Key-->Value 键值对一一对应
       
 //使用数组的形式实现键值对的字典是有顺序限制的
       
 NSDictionary * unDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"name",@"1",@"two",@"2",@"three",@"3", nil];
       
 //OC中字典中的元素是以键值对形式存储
       
 //@“name”-->@"1"
       
 //@"two"-->@"2"
       
 //@"three"-->@"3"
       
 //后者是键,前者是值
       
 //键值对的值和键,都是任意的对象,但是键通常使用字符串
       
 //字典存储对象的地址没有顺序
       
 NSLog(@"%@",unDict);
       
 //使用枚举遍历
       
 //键遍历
       
 NSEnumerator * keyenum = [unDict keyEnumerator];
       
 //值遍历
       
 NSEnumerator * valueenum = [unDict objectEnumerator];
       
 id obj ;
       
 while (obj =[keyenum nextObject]) {
           
 NSLog(@"%@",obj);
        }
       
 //for-each遍历
       
 for(id obj in valueenum){
           
 NSLog(@"%@",obj);
            NSLog(@"%@",[unDict objectForKey:obj]);
        }
       
 for(id obj in unDict){
           
 NSLog(@"%@",unDict);
        }
       
 //用键找值
       
 NSString * values = [unDict objectForKey:@"1"];
       
 NSLog(@"%@",values);

可变字典
       //可变字典是可以通过 单独添加的方法进行的
        NSMutableDictionary *mudirt = [[NSMutableDictionary alloc] init];
       
 //动态设置键值,相当于Java中的put方法
        [mudirt
 setObject:@"one" forKey:@"1"];
        [mudirt
 setObject:@"two" forKey:@"2"];
        [mudirt
 setObject:@"three" forKey:@"3"];
        [mudirt
 setObject:@"for" forKey:@"4"];
       
 NSLog(@"%@",mudirt);
        [mudirt
 removeObjectForKey:@"1"];
//        [mudirt removeAllObjects];

0 0