oc中数组,字典,集合使用的备忘录

1 数组api测试结果总结

arrayByAddingObject会创建新数组,在for循环中不建议使用;

[muteArray removeObjectsInArray:arr] : 将arr中包含的元素从muteArray中删除;不建议使用,数据重复时,不容易理清思路

数组遍历:

for...in:  常用且效率高;

for (NSInteger i = 0; i < count; i++):  较慢,方便获取索引值(swift已经弃用),在需要数据量小且需要改变数组时可以考虑使用;

enumerateObjectsWithOptions:  很慢,优势在于可以处理并发情况,其次在处理字典时可以轻松遍历字典,且在遍历字典时enumerateObjectsWithOptions提供了键值对,在处理数据方便的同时也节省一部分时间;

2 数组排序

[array sortedArrayUsingSelector:@selector(compare:)],一般用于字符串元素进行排序,测试可以对普通数据类型元素进行排序,

灵活使用sortedArrayUsingComparator,可以轻松实现数组中对象根据对象某个属性来排序,注意使用NSComparisonResult时,使用字符串来比较;

  NSComparisonResult result = [[NSString stringWithFormat:@"%ld",(long)obj1.num] compare:[NSString stringWithFormat:@"%ld",(long)obj2.num]]

使用NSSortDescriptor实现高级排序:

  NSSortDescriptor在构建时,key值必须为需要排序的数组中的对象存在的属性,或者此属性对应类中存在的属性(可直接使用点语法来获取),不存在则排序运行后会报错‘

this class is not key value’;

  sortedArrayUsingDescriptors返回的数组将按照传入的key值依此排序,第一个key值相同,则按照第二个key值排序;

汉字排序:

  最简易实现方式,待优化(应该将转为拼音读方法提炼成一个函数),此方法和网络上NSSortDescriptor大同小异,直接转为拼音比较可能有隐藏的坑:

[TestArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

        NSMutableString *one = [[NSMutableString alloc] initWithString:obj1];

        NSMutableString *two = [[NSMutableString alloc] initWithString:obj2];

        if (CFStringTransform((__bridge CFMutableStringRef)one, 0, kCFStringTransformMandarinLatin, NO)) {

            NSLog(@"pinyin1: %@", one);

        }

        if (CFStringTransform((__bridge CFMutableStringRef)two, 0, kCFStringTransformMandarinLatin, NO)) {

            NSLog(@"pinyin2: %@", two);

        }

 //转拼音后比较

        NSComparisonResult result1 = [[NSString stringWithFormat:@"%@",one] compare:[NSString stringWithFormat:@"%@",two]];

        return  result1;

   

    }];

  

stringByFoldingWithOptions可以将字符串转为规定的叠加格式后再使用sortedArrayUsingSelector对数组中的字符串排序,根据

NSStringCompareOptions这个枚举来决定排序的规则,如NSNumericSearch根据数字排序等;

原文地址:https://www.cnblogs.com/hazhede/p/8392311.html