数组和字典

一、数组和数组排序

1.创建数组


1// 创建一个空的数组  

2NSArray *array = [NSArray array];      

3// 创建有1个元素的数组  

4array = [NSArray arrayWithObject:@"123"];  

5// 创建有多个元素的数组  

6array = [NSArray arrayWithObjects:@"a"@"b"@"c", nil nil];  

7NSArray *array3 = [array arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:@"4"@"5", nil nil]];  

8   

9NSArray *array4 = [NSArray arrayWithObjects:@"1"@"2"@"3"@"4", nil nil];  

10NSRange range = NSMakeRange(1, 2);  

11NSArray *array5 = [array4 subarrayWithRange:range];  




2.数组的一些基本方法

1int count = [array count];//个数  

2// 判断是否包含了某个元素  

3if ([array containsObject:@"a"]) {  

4    NSLog(@"包含了字符串a");  

5 }  

6NSString *last = [array lastObject];最后一个元素  

7NSString *str = [array objectAtIndex:1];根据索引获取数组中的元素  

8int index = [array indexOfObject:@"c"];获取指定元素的索引  

9// 让数组里面的所有对象都调用test方法,123为参数  

10NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, nil nil];  

11[array makeObjectsPerformSelector:@selector(test2:) withObject:@"123"];  

12NSArray *array = [NSArray arrayWithObjects:@"1"@"2"@"3"@"4", nil nil];  

13// 1-2-3-4  

14// 利用分隔符-拼接所有的数组元素  

15NSString *str = [array componentsJoinedByString:@"-"];  

16// 将一个数组写入文件(生成的是一个xml文件)  

17NSString *path = @"/Users/apple/Desktop/array.xml";  

18[array writeToFile:path atomically:YES];  

19path = @"/Users/apple/Desktop/array.txt";  

20// 从文件中读取数组内容(文件有严格的格式要求)  

21NSArray *array2 = [NSArray arrayWithContentsOfFile:path];  


3.遍历数组

1#pragma mark 遍历数组1  

2void arrayFor1() {  

3    NSArray *array = [NSArray arrayWithObjects:stu1, @"1"@"2"@"3", nil nil];  

4    int count = array.count;  

5    for (int i = 0; i<count; i++) {  

6        id obj = [array objectAtIndex:i];  

7    }  

8 }  

9   

10#pragma mark 遍历数组2 快速遍历  

11void arrayFor2() {  

12    Student *stu1 = [Student student];  

13    NSArray *array = [NSArray arrayWithObjects:stu1, @"1"@"2"@"3", nil nil];  

14    int i =0;  

15    for (id obj in array) {  

16        NSLog(@"%i-%@", i, obj);  

17        i++;  

18    }  

19}  

20  

21#pragma mark 遍历数组3  

22void arrayFor3() {  

23    Student *stu1 = [Student student];  

24    NSArray *array = [NSArray arrayWithObjects:stu1, @"1"@"2"@"3", nil nil];  

25    [array enumerateObjectsUsingBlock:  

26     ^(id obj, NSUInteger idx, BOOLBOOL *stop) {  

27        NSLog(@"%i-%@", idx, obj);  

28         // 如果索引为1,就停止遍历  

29         if (idx == 1) {  

30             // 利用指针修改外面BOOL变量的值  

31             *stop = YES;  

32         }  

33    }];  

34}  

35  

36#pragma mark 遍历数组4  

37void arrayFor4() {  

38    Student *stu1 = [Student student];  

39    NSArray *array = [NSArray arrayWithObjects:stu1, @"1"@"2"@"3", nil nil];  

40    // 获取数组的迭代器  

41    // NSEnumerator *enumerator = [array objectEnumerator];  

42    // 反序迭代器(从尾部开始遍历元素)  

43    NSEnumerator *enumerator = [array reverseObjectEnumerator];  

44    // allObjects是取出没有被遍历过的对象  

45    NSArray *array2 = [enumerator allObjects];  

46    NSLog(@"array2:%@", array2);  

47    // 获取下一个需要遍历的元素  

48    id obj = nil;  

49    while (obj = [enumerator nextObject]) {  

50        NSLog(@"obj=%@", obj);  

51    } } 




4.数组排序


1#pragma mark 数组排序1  

2void arraySort1() {  

3    NSArray *array = [NSArray arrayWithObjects:@"2"@"3"@"1"@"4", nil nil];  

4      

5    // 返回一个排好序的数组,原来数组的元素顺序不会改变  

6    // 指定元素的比较方法:compare:  

7    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compare:)];  

8    NSLog(@"array2:%@", array2);  

9 }  

10  

11#pragma mark 数组排序2  

12void arraySort2() {  

13    Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li"];  

14    Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang"];  

15    Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li"];  

16    Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao"];  

17    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  

18    // 指定排序的比较方法  

19    NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];  

20    NSLog(@"array2:%@", array2);  

21}  

22- (NSComparisonResult)compareStudent:(Student *)stu {  

23    // 先按照姓排序  

24    NSComparisonResult result = [self.lastname compare:stu.lastname];  

25    // 如果有相同的姓,就比较名字  

26    if (result == NSOrderedSame) {  

27        result = [self.firstname compare:stu.firstname];  

28    }  

29    return result;  

30}  

31 1#pragma mark 数组排序3  

2void arraySort3() {  

3    Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li"];  

4    Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang"];  

5    Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li"];  

6    Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao"];  

7    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  

8      

9    // 利用block进行排序  

10    NSArray *array2 = [array sortedArrayUsingComparator:  

11     ^NSComparisonResult(Student *obj1, Student *obj2) {  

12         // 先按照姓排序  

13         NSComparisonResult result = [obj1.lastname compare:obj2.lastname];  

14         // 如果有相同的姓,就比较名字  

15         if (result == NSOrderedSame) {  

16             result = [obj1.firstname compare:obj2.firstname];  

17         }  

18           

19         return result;  

20    }];  

21      

22    NSLog(@"array2:%@", array2);  

23}  

24  

25#pragma mark 数组排序4-高级排序  

26void arraySort4() {  

27    Student *stu1 = [Student studentWithFirstname:@"MingJie" lastname:@"Li" bookName:@"book1"];  

28    Student *stu2 = [Student studentWithFirstname:@"LongHu" lastname:@"Huang" bookName:@"book2"];  

29    Student *stu3 = [Student studentWithFirstname:@"LianJie" lastname:@"Li" bookName:@"book2"];  

30    Student *stu4 = [Student studentWithFirstname:@"Jian" lastname:@"Xiao" bookName:@"book1"];  

31    NSArray *array = [NSArray arrayWithObjects:stu1,stu2,stu3, stu4, nil nil];  

32      

33    // 1.先按照书名进行排序  

34    // 这里的key写的是@property的名称  

35    NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES];  

36    // 2.再按照姓进行排序  

37    NSSortDescriptor *lastnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastname" ascending:YES];  

38    // 3.再按照名进行排序  

39    NSSortDescriptor *firstnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstname" ascending:YES];  

40    // 按顺序添加排序描述器  

41    NSArray *descs = [NSArray arrayWithObjects:bookNameDesc, lastnameDesc, firstnameDesc, nil nil];  

42      

43    NSArray *array2 = [array sortedArrayUsingDescriptors:descs];  

44      

45    NSLog(@"array2:%@", array2);  

46}   



二、字典和字典排序

1.字典

字典使用Key-Value的形式储存数据。

字典中的对象储存没有顺序,使用key来表示每个对象。

cocoa框架中的字典:NSDictionary和NSMutableDictionary

NSMutableDictionary是NSictionary的子类,能使用其所有方法。

NSMutableDictionary是NSDictionary的可修改版本



#import


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

{


    @autoreleasepool {

        //不可变字典NSDictionary

        //字典的创建

        NSDictionary *dic1=[NSDictionary dictionaryWithObject:@"velue" forKey:@"k1"];//一个键 一个值

        NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5",nil];//创建多个键 多个值

        NSDictionary *dic3=[NSDictionary dictionaryWithDictionary:dic1];//直接把dic内容给dic3

        NSLog(@"dic1:%@",dic1);

        NSLog(@"dic2:%@",dic2);

        NSLog(@"dic3:%@",dic3);

        

        //获取字典的数量

        int count=[dic2 count];

        NSLog(@"%d",count);

        //获取k3的value

        NSString *string=[dic2 objectForKey:@"k3"];

        NSLog(@"value:%@",string);

        

        //获取字典中所有的key和value

        NSArray *keyArray=[dic2 allKeys];

        NSArray *valueArry=[dic2 allValues];

        NSLog(@“keyArray:%@valueArry:%@",keyArray,valueArry);

//可变字典NSMutableDictionary

        NSMutableDictionary *mutableDic1=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5", nil];

        //上面是类方法直接赋值 下面是实例方法开辟空间并赋值

        NSMutableDictionary *mutableDic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"v1",@"k1",@"v2",@"k2",@"v3",@"k3",@"v4",@"k4",@"v5",@"k5", nil];

        

        //将一个字典中的velue和key添加到另外一个字典中

        NSDictionary *dic4=[NSDictionary dictionaryWithObject:@"v6" forKey:@"k6"];

        [mutableDic addEntriesFromDictionary:dic4];

        NSLog(@"MutableDic%@",mutableDic);

        

        //向字典中添加新的velue和key

        [mutableDic setValue:@"object" forKey:@"key"];

        NSLog(@"%@",mutableDic);

        

        

        //创建一个空的字典数组

        NSMutableDictionary *mutableDic2=[NSMutableDictionary dictionary];

        [mutableDic2 setDictionary:mutableDic];//

        NSLog(@"dic2:%@",mutableDic2);

        

        //通过制定key删除

        [mutableDic2 removeObjectForKey:@"k4"];

        NSLog(@"dic2:%@",mutableDic2);

        

        //删除多个键值

        NSArray *keys=[NSArray arrayWithObjects:@"k1",@"k2",@"k3", nil];

        [mutableDic2 removeObjectsForKeys:keys];

        NSLog(@"dic2:%@",mutableDic2);

        

        

        //删除全部键值

//        [mutableDic2 removeAllObjects];

//        NSLog(@"dic2:%@",mutableDic2);


  //遍历字典  一般的方法

        for (int index=0;index<[mutableDic1 count]; index++) {

            NSString *object=[mutableDic1 objectForKey:[[mutableDic1 allKeys]objectAtIndex:index]];

            NSLog(@"object:%@",object);

        }

        //快速枚举

        NSLog(@"____________________");

        for (NSString *key in mutableDic1) {

            NSString *object=[mutableDic1 objectForKey:key];

            NSLog(@"object:%@",object);

        }

        NSLog(@"____________________");

        //使用枚举类型

        NSEnumerator *enumerator=[mutableDic1 keyEnumerator];

        id key;

        while(key=[enumerator nextObject]){

            id object=[mutableDic1 objectForKey:key];

            NSLog(@“object:%@",object);  

        }      

    }

    return 0;

}



2.字典的排序

#import <foundation foundation.h="">

 

intmain(intargc, constchar* argv[]) {

    @autoreleasepool{

        // 1.定义一个测试的字典数组

        NSMutableArray *dictArray = @[

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:0],

                                          @"FOrder" : [NSNumber numberWithInt:0],

                                          @"FName" : @"宝玉"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:1],

                                          @"FOrder" : [NSNumber numberWithInt:0],

                                          @"FName" : @"黛玉"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:0],

                                          @"FGroupTag" : [NSNumber numberWithInt:1],

                                          @"FOrder" : [NSNumber numberWithInt:1],

                                          @"FName" : @"宝钗"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:1],

                                          @"FOrder" : [NSNumber numberWithInt:2],

                                          @"FName" : @"湘云"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:2],

                                          @"FOrder" : [NSNumber numberWithInt:0],

                                          @"FName" : @"妙玉"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:3],

                                          @"FOrder" : [NSNumber numberWithInt:0],

                                          @"FName" : @"晴雯"

                                          },

                                      @{

                                          @"FEnabled" : [NSNumber numberWithInt:1],

                                          @"FGroupTag" : [NSNumber numberWithInt:3],

                                          @"FOrder" : [NSNumber numberWithInt:1],

                                          @"FName" : @"袭人"

                                          }

                                       

                                      ];


// NSArray 转成 NSMutableArray

        // 0、对于不启用的,即enabled为0的字典模型,删除掉

        NSMutableArray *dictArr = [NSMutableArray array];

        for(inti = 0; i < dictArray.count; i++) {

            NSDictionary *dict = dictArray[i];

            if([[dict objectForKey:@"FEnabled"]intValue] == 1) {

                [dictArr addObject:dict];

            }

        }

        // NSLog(@"清除未启用的字典后的数组:%@",dictArr);

         

        // 1、对数组按GroupTag排序

        NSArray *sortDesc = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"FGroupTag"ascending:YES]];

        NSArray *sortedArr = [dictArr sortedArrayUsingDescriptors:sortDesc];

        // NSLog(@"排序后的数组:%@",sortedArr);

         

         

        // 2、对数组进行分组,按GroupTag

        // 遍历,创建组数组,组数组中的每一个元素是一个模型数组

        NSMutableArray *_groupArr = [NSMutableArray array];

        NSMutableArray *currentArr = [NSMutableArray array];

        NSLog(@"class--%@",[currentArr class]);

        // 因为肯定有一个字典返回,先添加一个

        [currentArr addObject:sortedArr[0]];

        [_groupArr addObject:currentArr];

        // 如果不止一个,才要动画添加

        if(sortedArr.count > 1){

            for(inti = 1; i < sortedArr.count; i++) {

                // 先取出组数组中  上一个模型数组的第一个字典模型的groupID

                NSMutableArray *preModelArr = [_groupArr objectAtIndex:_groupArr.count-1];

                intpreGroupID = [[[preModelArr objectAtIndex:0] objectForKey:@"FGroupTag"] intValue];

                // 取出当前字典,根据groupID比较,如果相同则添加到同一个模型数组;如果不相同,说明不是同一个组的

                NSDictionary *currentDict = sortedArr[i];

                intgroupID = [[currentDict objectForKey:@"FGroupTag"] intValue];

                if(groupID == preGroupID) {

                    [currentArr addObject:currentDict];

                }else{

                    // 如果不相同,说明 有新的一组,那么创建一个模型数组,并添加到组数组_groupArr

                    currentArr = [NSMutableArray array];

                    [currentArr addObject:currentDict];

                    [_groupArr addObject:currentArr];

                }

            }

        }

 // 3、遍历 对每一组 进行排序

        NSMutableArray *tempGroupArr = [NSMutableArray array];

        for(NSMutableArray *arr in _groupArr) {

            NSArray *sortDesc = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"FOrder"ascending:YES]];

            NSMutableArray *tempArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

                if([[obj1 objectForKey:@"FOrder"]intValue] < [[obj2 objectForKey:@"FOrder"]intValue]){

                    return NSOrderedAscending;

                }

                if([[obj1 objectForKey:@"FOrder"]intValue] > [[obj2 objectForKey:@"FOrder"]intValue]){

                    return NSOrderedDescending;

                }

                return NSOrderedSame;

            }];

            [tempGroupArr addObject:tempArr];

        }

        _groupArr = tempGroupArr;

         

        NSLog(@"封装好的group数组:%@",_groupArr);

    }

    return0;

}

</foundation>