OC中的NSArray和NSMutableArray、NSDictionary和NSMutableDictionary用法

一:NSArray 和NSMutableArray
1: NSArray:不可变数组
   NSArray是OC中使用的数组,只能用来存放OC对象,不能存放非OC对象如基本数据类型
      它使不可变的,一旦初始化完毕,内容不能改变,也不能添加元素。
      而C语言中的数组只能存放一种数据类型
  (1) 普通数组的用法
// 普通数组的创建
//        int arr[5] = {1,3,4};
        
        // 对象数组的创建
//        Person *p = [[Person alloc] init];
//        Person *arrP[5] = {p, [[Person alloc] init]};
        

(2):NSArray的创建

 
        // 0,创建的数组对象永远都是空数组,也就没有任何意义,因为NSArray是不可变的
//        NSArray *arr1 = [NSArray array];
        
        // 1, 创建只有一个对象的数组
//        NSArray *arr2 = [NSArray arrayWithObject:p];
//        NSLog(@"%ld", arr2.count); // 结果 1
        
        // 2, 创建多了对象的数组,注意nil必须填写,数组元素什么时候结束
//        NSArray *arr3 = [NSArray arrayWithObjects:@"12", @"34", nil];
//        NSLog(@"%ld", arr3.count); //结果:2
        
        // 3,快速创建一个NSArray
//        NSArray *arr4 = @[@"12", @"34"];
//        NSLog(@"%@", arr4); // 结果: (12,34)
        

(3)OC数组的访问

// 获取数组中元素的个数
//        NSArray *arr5 = @[@"hello", @"world", @"china"];
//        NSLog(@"%ld", arr5.count); // 结果 3
//        
//        // 访问数组中指定位置的元素
//        NSString *str = [arr5 objectAtIndex:2];
//        NSLog(@"%@", str); // china
//        
//        // 快速访问数据指定位置的元素值
//        NSString *str2 = arr5[1];
//        NSLog(@"%@", str2); // 结果:world
//        
//        // 查找指定元素的位置
//        NSUInteger index = [arr5 indexOfObject:@"hello"];
//        NSLog(@"index = %ld", index); // 结果 0;
        
          // 获取第一个元素
//          id str = [arr5 firstObject];
//          NSLog(@"%@", str);
        
         //  获取最后一个元素
//        id  str = [arr5 lastObject];
//        NSLog(@"%@", str);
//        
//        // 判断数组中是否存在摸个元素
//        BOOL b = [arr5 containsObject:@"hello"];
//        NSLog(@"%d", b);
        

(4)OC数组的遍历

// 1,通过for循环简单遍历
//        NSArray *arr6 = @[@"hello", @"china", @"world"];
////        for (int i = 0; i<arr6.count; i++) {
//////            NSLog(@"%@", [arr6 objectAtIndex:i]);
////            NSLog(@"%@", arr6[i]);
////        }
//        
//        // 2,通过for in进行遍历
////        for (NSString *str in arr6) {
////            NSLog(@"%@", str);
////        }
//        
//        // 3,通过数组的方法 Block
//        [arr6 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//            if (idx == 1) {
//                *stop = YES;
//            }
//            NSLog(@"%@----%ld", obj, idx);
//        }];
        /**
         *  这个方法是每遍历到一个元素,就把这个元素还有索引当做一个参数传给Block
         */
        // enumerateObjectsUsingBlock遍历的深入研究,内部是怎么实现的
//        void(^myBlock)(id obj, NSUInteger idx, BOOL *stop) = ^(id obj, NSUInteger idx, BOOL *stop){
//            NSLog(@"%@----%ld", obj, idx);
//            if (idx == 1) {
//                *stop = YES;
//            }
//        };
//        for (int i = 0; i<arr6.count; i++) {
//            
//            id obj = arr6[i];
//            BOOL isStop = NO;
//            myBlock(obj, i, &isStop);
//            if (isStop) {
//                
//                break;
//            }
//        }

(5)OC数组给数组中的所有元素发送消息及带一个参数的消息

Person *p1 = [[Person alloc] init];
//        p1.name = @"张伯伦";
//        
//        Person *p2 = [[Person alloc] init];
//        p2.name = @"乔丹";
//
//        Person *p3 = [[Person alloc] init];
//        p3.name = @"奥尼尔";
//
//        NSArray *arr = @[p1, p2, p3];
//        [arr makeObjectsPerformSelector:@selector(sayHi)];
//        [arr makeObjectsPerformSelector:@selector(say:) withObject:@"你好"];
        /**
         *  这个方法会向数组中存放的每一个对象发送消息,不过只能有一个参数的消息方法
         */
        

(6)OC数组的文件夹的读取操作:

        // NSArray 只能写入字符串类型的数据,,NSDictionary才可以写对象到文件,在苹果开发中,遇到xml文件,可以把后缀该为.plist,这样就可以使用xcode打开编辑了。
//        NSArray *arr6 = @[@"hello", @"china", @"world"];
//        NSLog(@"%d",[arr6 writeToFile:@"/Users/ll/Desktop/text.plist" atomically:YES]);
//        NSArray *arr = [NSArray arrayWithContentsOfFile:@"/Users/llDesktop/text.plist" ];
//        NSLog(@"%@", arr);
        

(7)NSString和NSArray

        NSArray *array = @[@"乔丹", @"科比", @"加内特"];
        
        // 将数组用一个指定的字符串拼接起来
//        NSString *str = [array componentsJoinedByString:@"NBA"];
        
        // 将字符串带⭐️字符串分割成一个数组
//        NSString *str = @"乔丹⭐️科比⭐️加内特";
//        NSArray *array2 = [str componentsSeparatedByString:@"⭐️"];
//        NSLog(@"%@", array2);
        
2 > NSMutableArray的用法
   创建添加删除元素(它是一个可变数组)
        // 创建一个可变数组
        // 添加元素
//        NSMutableArray *arrM = [NSMutableArray arrayWithObject:@"world"];
//        [arrM addObject:@"hello"];
//        
//        // OC数组不能添加nil对象 错误
////        [arrM addObject:nil];
//        
//        // 删除元素
////        [arrM removeObject:@"hello"];
////        [arrM removeAllObjects];
//          // 删除指定位置的元素
//        [arrM removeObjectAtIndex:1];
//        NSLog(@"%@", arrM);
        
        // 替换元素
//        NSArray *array1 = @[@"a", @"b", @"c"];
//        NSMutableArray *arrM = [NSMutableArray arrayWithArray:array1];
//        [arrM replaceObjectAtIndex:1 withObject:@"m"];
//        [arrM exchangeObjectAtIndex:1 withObjectAtIndex:2];
//        NSLog(@"%@", arrM);
        
注意:
  • NSMutableArray *array = @[@"bob", @"steve", @"john"];

  • [array addObject:@“Peter”];// 错误,使⽤用@[@"bob", @"steve", @"john"]这种⽅方式 创建的永远是NSArray(不可变数组)

  • //正确

  • NSMutableArray *array = [NSMutableArray arrayWithArray:@[@"bob",

    @"steve", @"john"]];

  • [array addObject:@"Peter”];

    二:NSDictionary

    什么是NSDictionary

    ➢ NSDictionary翻译过来叫做”字典”

    ➢ ⽇日常⽣生活中, “字典”的作⽤用: 通过⼀一个拼⾳音或者汉字, 就能找到对应的详细解 释

    ➢ NSDictionary的作⽤用类似: 通过⼀一个key, 就能找到对应的value ➢ NSDictionary是不可变的, ⼀一旦初始化完毕, ⾥里⾯面的内容就⽆无法修改

    1)不可变字典的创建

  •         // 1,创建字典及初始化, 不可变
            // 没有任何意义
    //        NSDictionary *dic = [NSDictionary dictionary]; //
            
            // 创建只有一个键值对的字典
    //        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"yaoming"
    //            forKey:@"ym"];
            // 创建多个键值对字典
    //        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"liuxiang", @"lx", @"tianliang", @"tl", nil];
            
    //        // 快速创建方法
    //        NSDictionary *dic = @{@"ym":@"yaoming", @"lx":@"liuxiang"};
    //        NSLog(@"%@", dic);
            

    2)字典的访问

  • // 2,字典访问
    //        NSDictionary *dict = @{@"zs" : @"zhangsan", @"ls" : @"lisi", @"ww" : @"Wangwu"};
            
            // 返回字典中的键值数目 count
    //        NSUInteger length = dict.count;
            
            // 根据键求值
    //        id str = [dict objectForKey:@"zs"];
                // 快速访问
    //        id str = dict[@"zs"];
    //        NSLog(@"str = %@", str);
            

    3)字典的遍历

  •         // 3,字典的遍历
    //        NSDictionary *dict = @{@"zs" : @"zhangsan", @"ls" : @"lisi", @"ww" : @"Wangwu"};
            
            // for循环
    //        id key = [dict allKeys]; // 可以知道字典中所有的值
    //        for (int i = 0; i<dict.count; i++) {
    //            
    //            id str = dict[key[i]];
    //            NSLog(@"%@:%@", key[i], str);
    //        }
            
            // for in遍历字典中的所有的键
    //        for (NSString  *key in dict) {
    //            
    //            id str = dict[key];
    //            NSLog(@"%@:%@", key, str);
    //        }
            
            // Block
    //        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    //            NSLog(@"%@:%@", key, obj);
    //        }];

    4)字典读取文件的操作

  •         // 4,把字典写入到文件
    //        NSDictionary *dict = @{@"zs" : @"zhangsan", @"ls" : @"lisi", @"ww" : @"Wangwu"};
    //        
    //        [dict writeToFile:@"/Users/ll/Desktop/te.plist" atomically:YES];
            
            // 用字典读取文件
    //        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:@"/Users/ll/Desktop/te.plist"];
    //        NSLog(@"%@", dic);
            
  • 注意:字典中的键不要重复。(虽然重复也不报错,会⾃自动取在前⾯面的那个)

    2,NSMutableDictionary

    • 什么是NSMutableDictionary

    ➢ NSMutableDictionary是NSDictionary的⼦子类

    ➢ NSDictionary是不可变的, ⼀一旦初始化完毕后, 它⾥里⾯面的内容就永远是固定 的, 不能删除⾥里⾯面的元素, 也不能再往⾥里⾯面添加元素

    ➢ NSMutableDictionary是可变的, 随时可以往⾥里⾯面添加更改删除元素

     NSMutableDictionary的用法

            // 1,创建一个空的可变字典
            NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
            [dicM setObject:@"zhangsan" forKey:@"zs"];
            
            // 2,删除指定键值对
    //        [dicM removeObjectForKey:@"zs"];
            
            // 3,删除字典中所有内容
            [dicM removeAllObjects];
            NSLog(@"%@", dicM);
            /**
             *  注意:@{键:值}创建的字典为不可变字典 ,不用赋值给可变字典及后续操作
             */
原文地址:https://www.cnblogs.com/-boy/p/4096453.html