objective-c基础语法之字典NSDIctionary、NSMutableDictionary

  • 不可变字典NSDictionary的创建
    //创建一个空字典
    NSDictionary *dic = [[NSDictionary alloc]init];
    //根据本地文件创建一个字典
    NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:(NSString *)];
    //根据网址URL创建一个字典
    NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfURL:(NSURL *)];
    //根据已知字典创建一个新的字典
    NSDictionary *dic = [[NSDictionary alloc]initWithDictionary:(NSDictionary *)];
    
    //根据值的集合数组与键的集合数组创建一个字典
    NSDictionary *dic = [[NSDictionary alloc]initWithObjects:(NSArray *) forKeys:(NSArray *)];
    //使用如下:
    NSArray *arr_values = [[NSArray alloc]initWithObjects:@"Mary","female", nil];
        NSArray *arr_keys = [[NSArray alloc]initWithObjects:@"name","sex", nil];
        NSDictionary *dic = [[NSDictionary alloc]initWithObjects:arr_values forKeys:arr_keys];
     
  • 不可变字典与可变字典的创建方式不同的方法如下:
    //创建容量初始为多少的字典
    NSMutableDictionary *mutable_dic = [[NSMutableDictionary alloc]initWithCapacity:(NSUInteger)];
    //使用如下:

    NSMutableDictionary *mutable_dic = [[NSMutableDictionary alloc]initWithCapacity:0];

     
  • 读取字典中的数据
    //读取字典中的值
    [mutable_dic objectForKey:(id)];
    //读取键为@"name"对应的值
    [mutable_dic objectForKey:@"name"];
    
    //获取字典的长度
    [mutable_dic count];
    
    //获取字典中所有的键值
    [mutable_dic allKeys];
     

相关推荐