美文网首页
iOS NSDictionary和NSMutableDictio

iOS NSDictionary和NSMutableDictio

作者: 清风_____ | 来源:发表于2020-10-29 18:02 被阅读0次

    1、Objective-C

    // 1.方法一(不可变字典)
            NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:@"a",@"1",@"b",@"2", nil];
            NSLog(@"%@",dic);
    //2.方法二(不可变字典)
          NSDictionary *dic01 = [NSDictionary dictionaryWithObjectsAndKeys:@"a",@"1",@"b",@"2",@"c",@"3", nil];
            NSLog(@"%@",dic01);
    
    //可变字典初始化
            NSMutableDictionary *dic03 = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"1",@"a",@"2",@"b",@"3",@"c", nil];
            NSLog(@"dic03 = %@",dic03);
     
           //增加键值对
            [dic03 setValue:@"4" forKey:@"d"];
            NSLog(@"%@",dic03);
            
            //删除键值对
            [dic03 removeObjectForKey:@"d"];
             NSLog(@"%@",dic03);
            
            //修改value的值
            [dic03 setObject:@"2" forKey:@"a"];
             NSLog(@"%@",dic03);
    

    2、swift

    //空字典创建
    var someDict = [Int: String]()
    
    //非空字典创建
    var dic:[String:String] = ["a":"1","b":"2","c":"3"]
    
    //添加数据(updateValue(forKey:) 增加或更新字典的内容。如果 key 不存在,则添加值,如果存在则修改 key 对应的值)
    dic.updateValue("4", forKey: "d")
    
    //修改
    dic.updateValue("5", forKey: "d")
    
    //删除数据(removeValueForKey() 方法来移除字典 key-value 对。如果 key 存在该方法返回移除的值,如果不存在返回 nil )
    dic.removeValue(forKey: "d")
    
    print( "dic = \(dic), str = \(str)" )
    

    相关文章

      网友评论

          本文标题:iOS NSDictionary和NSMutableDictio

          本文链接:https://www.haomeiwen.com/subject/juqlvktx.html