oc75--不可变字典NSDictionary

//
//  main.m
//  NSDictionary
//
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {

    // 1.如何创建
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"lnj" forKey:@"name"];
    NSString *name1 = [dict1 objectForKey:@"name"];
    NSLog(@"name = %@", name1); //lnj
    NSLog(@"dict1 = %@", dict1);    //dict1 = {name = lnj;}

    
    
    
    // 注意: key和value 是一一对应
    NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:@[@"lnj", @"30", @"1.75"] forKeys:@[@"name", @"age", @"height"]];
    NSLog(@"dict2 = %@", dict2);    //{age = 30;height = "1.75";name = lnj;}

    NSLog(@"%@ %@ %@", [dict2 objectForKey:@"name"], [dict2 objectForKey:@"age"], [dict2 objectForKey:@"height"]);
    
    //NSDictionary *dict3 = @{key:value};
    NSDictionary *dict4 = @{@"name": @"lnj"};
    NSLog(@"%@", dict4[@"name"]);
    
    NSDictionary *dict5 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"};
    NSLog(@"dict5 = %@", dict5);//{age = 30;height = "1.75";name = lnj;}
    NSLog(@"%@ %@ %@", dict5[@"name"], dict5[@"age"], dict5[@"height"]);
    
    // 2.字典的遍历
    NSDictionary *dict6 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"};
    // 2.1如何获取字典中key和value的个数, 在字典中key称之为键, value称之为值
    NSLog(@"count = %lu", [dict6 count]);
    
    
    for (int i = 0; i < dict6.count; ++i) {
        // 获取字典中所有的key
        NSArray *keys = [dict6 allKeys];
        // 取出当前位置对应的key
        NSLog(@"%@", keys[i]);
        NSString *key = keys[i];
        NSString *value = dict6[key];
        NSLog(@"key = %@, value = %@", key, value);
    }
    
    
    
    // 如何通过forin遍历字典, 会将所有的key赋值给前面的obj
    for (NSString *key in dict6) {
        NSLog(@"%@", key);
        NSString *value = dict6[key];
        NSLog(@"key = %@, value = %@", key, value);

    }
    
    
    
    [dict6 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"key = %@, value = %@", key, obj);
    }];
    
    
    // 3.字典文件读写
    NSDictionary *dict7 = @{@"name":@"lnj", @"age":@"30", @"height":@"1.75"};
    // XML 扩展名plist
    [dict7 writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES];
    
    // 注意: 字典和数组不同, 字典中保存的数据是无序的
    NSDictionary *newDict8 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/mctc/Desktop/a.plist"];
    NSLog(@"%@", newDict8);// {age = 30;height = "1.75";name = lnj;}
    
    
    NSArray *arr9 = @[@10, @20, @30, @5];
    [arr9 writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES];
    
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值