iOS中的NSDictionary和NSMutableDictionary

2023-11-22 09:02:01 浏览数 (2)

NSDictionary基本用法

代码语言:javascript复制
    //创建
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
    NSLog(@"%@",dic[@"key"]);

    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key",@"A",@"a",@"B",@"b",@"C",@"c", nil];
    NSLog(@"%@",dic1[@"key"]);
    
    NSDictionary *dic2 = @{@"key":@"value",@"a":@"A",@"b":@"B",@"c":@"C"};
    NSLog(@"%@",dic2[@"key"]);

键值对个数

代码语言:javascript复制
    NSLog(@"%lu",(unsigned long)[dic1 count]);//4
    NSArray *keys = [dic1 allKeys];
    NSLog(@"%@",keys);//b,key,c,a
    NSArray *values = [dic1 allValues];
    NSLog(@"%@",values);//B,value,C,A

遍历

代码语言:javascript复制
    [dic2 enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSLog(@"key:%@--obj:%@",key,obj);
    }];
    /*
     key:b--obj:B
     key:key--obj:value
     key:c--obj:C
     key:a--obj:A
     */

字典读写(无序)

代码语言:javascript复制
    BOOL flag = [dic2 writeToFile:@"/Users/soso/Desktop/demo1/NSArray/demo.plist" atomically:YES];
    NSLog(@"%d",flag);
    NSDictionary *dic3 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/soso/Desktop/demo1/NSArray/demo.plist"];
    NSLog(@"%@",dic3);
    /*
     a = A;
     b = B;
     c = C;
     key = value;
     */

NSMutableDictionary

代码语言:javascript复制
    //创建一个空字典
    NSMutableDictionary *dic4 = [NSMutableDictionary dictionary];
    //添加
    [dic4 setObject:@"value" forKey:@"key"];
    //将传入字典所有的键值对取出来添加到dic中
    [dic4 setValuesForKeysWithDictionary:@{@"key1":@"Value1"}];
    NSLog(@"%@",dic4);
    /*
     key = value;
     key1 = Value1;
     */
    
     //删除
    [dic4 removeObjectForKey:@"key1"];
    NSLog(@"%@",dic4);//key = value;

    [dic4 removeObjectsForKeys:@[@"key",@"key1"]];
    NSLog(@"%@",dic4);

    [dic4 removeAllObjects];
    
    //修改
    [dic4 setObject:@"newValue" forKey:@"key"];
    NSLog(@"%@",dic4);
    /*
     key = newValue;
     key1 = Value1;
     */

0 人点赞