zoukankan      html  css  js  c++  java
  • [好程序员训练营]Objective-C学习笔记---基本数据结构NSDictionary

        <A href="http://www.goodprogramme r.org/" target="blank">ios培训</A>------我的OC语言笔记,期待与您交流!

      前言:NSDictionary是OC中的字典类型,定义一个字典对象,那么这个字典对象里的数据时以键值对的形式存储的。相比于NSArray和NSString类型,他们三个都能够创建不可变对象和可变对象,并且创建方法也大致相同,但是NSDictionary类型更方便于查找元素,下面来看看NSDictionary如何创建不可变字典和可变字典

    一、NSDictionary创建不可变字典

     1    ///////////创建一个不可变字典///////////
     2     NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"xiaoming",@"1",@"xi    aohong",@"2",@"xiaogang",@"3", nil];
     3     NSLog(@"%@",dict);  //注意这儿打印输出的顺序和你往字典里添加键值对的顺序并不一致

    4 ///////////用枚举器法遍历字典//////////////// 5 NSEnumerator * enumerator = [dict keyEnumerator]; //将键装进枚举器 6 id key; 7 while(key=[enumerator nextObject]){ 8 NSLog(@"%@",key); //打印键 9 NSLog(@"%@",[dict objectForKey:key]); //通过键找到值 10 } 11 12 NSEnumerator * enumerator1 = [dict objectEnumerator];//将值装进枚举器 13 id obj; 14 while(obj=[enumerator1 nextObject]){ 15 NSLog(@"%@",obj); //直接打印值 16 } 17 18 /////////////////快速枚举法//////////////// 19 for(id key in dict){ 20 NSLog(@"%@",key); //打印键 21 NSLog(@"%@",[dict objectForKey:key]); //通过键找到值 22 }

    创建一个不可变字典过后,里面的键值对就固定了,不能再修改添加,只可进行查看

    二、NSMutableDictionary创建可变字典

    1     ///////////////创建一个可变字典/////////////////
    2     NSMutableDictionary *mdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"xiaomi      ng",@"1", nil];   
    3     
    4     [mdict setValue:@"xiaohong" forKey:@"2"]; //添加键值对
    5     NSLog(@"%@",mdict);
    6 
    7     [mdict removeObjectForKey:@"2"];          //删除键值对
    8     NSLog(@"%@",mdict);

    此外,可变字典也可以用不可变字典里那些查看字典的方法

  • 相关阅读:
    The Python Standard Library
    Python 中的round函数
    Python文件类型
    Python中import的用法
    Python Symbols 各种符号
    python 一行写多个语句
    免费SSL证书(https网站)申请,便宜SSL https证书申请
    元宇宙游戏Axie龙头axs分析
    OLE DB provider "SQLNCLI10" for linked server "x.x.x.x" returned message "No transaction is active.".
    The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "xxx.xxx.xxx.xxx" was unable to begin a distributed transaction.
  • 原文地址:https://www.cnblogs.com/ITLiu/p/4551135.html
Copyright © 2011-2022 走看看