• oc中的字典NSDictionary


     1 //字典和可变字典
     2    NSDictionary和NSMutableDictionary
     3    
     4    //创建
     5    NSDictionary *dict=[[NSDictionary alloc] initWithObjectsAndKeys:
     6        @"one",@"1",@"three",@"3",@"two",@"2",nil];
     7     //字典中的元素是以键值对的形式存储的。
     8     //@"one"(值=value)和@"1"(键=key)组成了一个键值对
     9    //键值对的值和键都是任意对象,但是键往往使用字符串
    10    //字典存储对象的地址没有顺序
    11    NSLog(@"%@",dict);
    12    //结果:
    13    //1=one;
    14    //2=two;
    15    //3=three;
    16    
    17    //枚举法遍历
    18    //键的遍历
    19    NSEnumerator *enumerator=[dict keyEnumerator];
    20    id obj;
    21    while(obj=[enumerator nextObject]){
    22     NSLog(@"%@",obj);//结果:132
    23    }
    24    //值的遍历
    25    NSEnumerator *enumerator=[dict objectEnumerator];
    26    id obj;
    27     while(obj=[enumerator nextObject]){
    28     NSLog(@"%@",obj);//结果:one three two
    29    }
    30    
    31    
    32    //快速枚举法
    33    for(id obj in dict){
    34     NSLog(@"%@",obj);//遍历的是键 
    35     NSLog(@"%@",[dict objectForKey:obj]);//得到值
    36    }
    37    //可以通过下面的语句通过键得到值
    38    NSString *str=[dict objectForKey:@"1"];
    39    
    40    
    41    [dict release];
    42    
    43    //可变字典
    44    //创建
    45    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    46    //添加
    47    [dict setObject:@"one" forKey:@"1"];
    48    [dict setObject:@"two" forKey:@"2"];
    49    //删除
    50    [dict removeObjectForKey:@"1"];
    51    
  • 相关阅读:
    图像滤波与OpenCV中的图像平滑处理
    OpenCV创建轨迹条,图片像素的访问
    模板类和友元的总结和实例验证
    C++中运算符重载
    C++之Stack模板类
    C++中explicit关键字的作用
    #ifdef-#endif的作用及其使用技巧
    ZOJ 3170 Friends
    ZOJ 3713 In 7-bit
    HDU 1421 搬寝室
  • 原文地址:https://www.cnblogs.com/sdutmyj/p/4555536.html
Copyright © 2020-2023  润新知