Oc-语句总结(3)--NSDictionary

来源:互联网 发布:淘宝批量上传淘宝联盟 编辑:程序博客网 时间:2024/06/14 14:48
❤简介:
              1.NSDictionary为字典,也是用来存储元素的,里面每一个元素都是以键值对的形式存在
              2.键值一一对应,通过一个键找到一个值
              3.键不可重复,值可以
1.一个元素的创建
    //创建一个元素的字典(键值对)
      NSDictionary *dict = [NSDictionarydictionaryWithObject:@"100"forKey:@"Score"];
      NSLog(@"%@",dict );
      输出结果:Score = 100;
 
2.多个元素的创建
    //字典多个元素的创建
     NSDictionary *dict1 = [NSDictionarydictionaryWithObjectsAndKeys:@"3",@"a",@"4",@"b",nil];
     NSLog(@"%@",dict1);
     输出结果:a = 3,b = 4;

3.简便方法(快速建立)
     1. //快速建立 格式@{}大括号
      NSDictionary *dict3 =@{@"a":@"3",@"b":@"4"};
      NSLog(@"%@",dict3);
      输出结果:a = 3;b = 4;
    2.求值
       NSString*str = dict3[@“a"]
    NSLog(@“a = %@“,str);
       输出结果:a = 3;
4.字典的遍历
    1.用法:forin增强for循环  ---NSString* obj = [dict3objectForKey:key];  
                                                —等同于NSString* obj = dict3[key]; (简便写法
              NSDictionary *dict3 =@{@"a":@"3",@"b":@"4"};
             //增强for循环遍历字典取得(key)
               for(NSString*key in dict3) {
              //取得key
              // NSLog(@"%@",key);
              //通过key键,获得值
              NSString * obj = [dict3objectForKey:key];               第一种方法
              NSString * obj = dict3[key];                                      第二种方法
              NSLog(@"key = %@,obj = %@",key,obj);
              
输出结果:key = a,obj =3 key = b,obj = 4
       
     2.block遍历
           NSDictionary*dict3 =@{@"a":@"3",@"b":@"4"};
              [dict3 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL* _Nonnull stop) {
              NSLog(@"key = %@,obj = %@",key,obj); }];
5.字典的读写文件与数组一样
6.可变字典
  详解:
            //可变空字典的创建
              NSMutableDictionary*dict = [NSMutableDictionarydictionary];
             
//添加元素                          
             [dict
setObject:@"yaya"forKey:@"a”];                 1
             
NSLog(@"%@",dict);
             
//输出结果:a = yaya;
            //删除元素--通过key删除value
            [dict removeObjectForKey:@"a"];
            NSLog(@"%@",dict);
            
//输出结果:
            
//清空-删除所有键值对
            [dict
removeAllObjects];
            
//简便方法
             dict[
@"ww"] =@"3”;                                          2
             
NSLog(@"%@",dict);
            //输出结果:    ww = 3;
   注:1等同于2
   

7.补充NSURL
  详解://路径
           NSURL *url = [NSURLURLWithString:@"file:///Users/mac/Desktop/1.txt/"];
           NSString*str = @"你好,世界!";
           
//str写入url布尔类型
           
BOOLresult =  [str writeToURL:url atomically:YESencoding:NSUTF8StringEncodingerror:nil];
           if (result) {
             NSLog(@"写入成功");}
            else {NSLog(@"写入失败");}






1 0