数组的排序及筛选

sortedArrayUsingComparator

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

NSLog(@"排序前: %@",array);

NSComparator comparator = ^(id obj1, id obj2){
    if([obj1 integerValue] > [obj2 integerValue])
    {
        return NSOrderedDescending;
    }
    if([obj1 integerValue] < [obj2 integerValue])
    {
        return NSOrderedAscending;
    }
    return NSOrderedSame;

    //return (arc4random() % 3) - 1; //随机排序
};

array = [array sortedArrayUsingComparator:comparator];

NSLog(@"排序后: %@",array);

sortedArrayUsingComparator

sortedArrayUsingFunction:customSort

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    NSLog(@"排序前: %@",array);

    array = [array sortedArrayUsingFunction:customSort context:nil];

    NSLog(@"排序后: %@",array);
}

NSInteger customSort(id obj1, id obj2, void* context)
{
     if ([obj1 integerValue] > [obj2 integerValue])
     {
         return NSOrderedDescending;
     }

     if ([obj1 integerValue] < [obj2 integerValue])
     {
         return NSOrderedAscending;
     }
     return NSOrderedSame;
}

sortedArrayUsingFunction:customSort

sortUsingDescriptors

#import <Foundation/Foundation.h>

@interface TopMenuItem : NSObject

@property (strong, nonatomic) NSString *title;
@property (assign, nonatomic) NSInteger order;
@property (assign, nonatomic) BOOL selected;

@end

#import "TopMenuItem.h"

@implementation TopMenuItem

- (NSString *)description
{
    return [NSString stringWithFormat:@"title:%@, order:%d, selected:%d",self.title,self.order,self.selected];
}

@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableArray *channelArray = [NSMutableArray array];

    TopMenuItem *item = [[TopMenuItem alloc] init];
    item.title = @"要闻";
    item.order = 1;
    item.selected = YES;
    [channelArray addObject:item];

    item = [[TopMenuItem alloc] init];
    item.title = @"半导体照明";
    item.selected = YES;
    item.order = 3;
    [channelArray addObject:item];

    item = [[TopMenuItem alloc] init];
    item.title = @"电子工程";
    item.selected = YES;
    item.order = 2;
    [channelArray addObject:item];

    item = [[TopMenuItem alloc] init];
    item.title = @"光通讯";
    item.selected = NO;
    item.order = 3;
    [channelArray addObject:item];

    NSLog(@"排序前");
    for (TopMenuItem *item in channelArray)
    {
        NSLog(@"%@",item);
    }

    NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:YES];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"selected" ascending:YES];

    [channelArray sortUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil]];

    NSLog(@"排序后");
    for (TopMenuItem *item in channelArray)
    {
        NSLog(@"%@",item);
    }
}

sortUsingDescriptors

makeObjectsPerformSelector

这个方法可以让数组内的所有元素都执行同一个对象方法,在特定场合可以替代for循环使用。

还是沿用上面例子里的TopMenuItem类,新加入一个方法:

- (void)testFun:(NSString *)str
{
    NSLog(@"testFun,param is:%@,title is %@",str,self.title);
}

然后就可以这样调用:

[channelArray makeObjectsPerformSelector:@selector(testFun:) withObject:@"测试"];

NSPredicate

Cocoa框架中的NSPredicate主要用于查询并过滤元素,比较类似于Sql语句中的where,使用方法如下:

NSArray *array = @[@"A",@"AB",@"ABC",@"D",@"DF"];

NSLog(@"排序前: %@",array);

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF Contains ‘A‘"];
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];

NSLog(@"排序后: %@",newArray);

如果是NSMutableArray,则可以直接调用filterUsingPredicate来过滤原数组。

比较运算符

>  >=  <  <=  ==  !=(或<>)

NSMutableArray *array = [NSMutableArray arrayWithArray:@[[NSNumber numberWithInt:1],
                                                         [NSNumber numberWithInt:4],
                                                         [NSNumber numberWithInt:23],
                                                         [NSNumber numberWithInt:999],
                                                         [NSNumber numberWithInt:83],]];

NSLog(@"原数组: %@",array);

NSString *filterString = @"SELF>50"; //get 83,999
filterString = @"SELF==23"; //get 23
filterString = @"SELF<=23"; //get 1,4,23

NSPredicate *predicate = [NSPredicate predicateWithFormat:filterString];

[array filterUsingPredicate:predicate];

NSLog(@"过滤后: %@",array);

Code

范围运算符

IN  BETWEEN

NSMutableArray *array = [NSMutableArray arrayWithArray:@[[NSNumber numberWithInt:1],
                                                         [NSNumber numberWithInt:4],
                                                         [NSNumber numberWithInt:23],
                                                         [NSNumber numberWithInt:999],
                                                         [NSNumber numberWithInt:83],]];

NSLog(@"原数组: %@",array);

NSString *filterString = @"SELF BETWEEN {4,50}"; //get 4,23
filterString = @"SELF IN {23,999}"; //get 23,999

NSPredicate *predicate = [NSPredicate predicateWithFormat:filterString];

[array filterUsingPredicate:predicate];

NSLog(@"过滤后: %@",array);

Code

字符串比较

LIKE  BEGINWITH  CONTAINS  ENDSWITH  MATCHES

NSArray *array = @[@"park",@"army",@"phone",@"warrior",@"stone",@"ear",@"apple",@"application",@"wear"];

NSString *filterString = @"SELF LIKE[cd] ‘*ar‘"; //get "ear","wear"

filterString = @"SELF LIKE[cd] ‘?ar‘"; //get "ear"

filterString = @"SELF LIKE[cd] ‘?ar?‘"; //get "park"

filterString = @"SELF LIKE[cd] ‘?ar*‘ && SELF ENDSWITH[cd] ‘r‘"; //get "warrior","ear"

filterString = @"SELF BEGINSWITH[cd] ‘e‘ || SELF BEGINSWITH[cd] ‘s‘"; //get "stone","ear"(匹配以"e"或"s"开头的单词)

filterString = @"SELF BEGINSWITH[cd] ‘app‘"; //get "apple","application"

filterString = @"SELF ENDSWITH[cd] ‘one‘"; //get "stone","phone"

filterString = @"SELF MATCHES[cd] ‘^w.+r$‘"; //get "warrior","wear"(正则匹配以"w"开头,"r"结尾的单词)

NSPredicate *predicate = [NSPredicate predicateWithFormat:filterString];

NSLog(@"过滤结果: %@",[array filteredArrayUsingPredicate:predicate]);

Code

上面的例子都是直接利用SELF比较,如果数组存储的是对象,要以对象的属性值作为筛选目标可以这样:

NSMutableArray *channelArray = [NSMutableArray array];

TopMenuItem *item = [[TopMenuItem alloc] init];
item.title = @"要闻";
item.order = 1;
item.selected = YES;
[channelArray addObject:item];

item = [[TopMenuItem alloc] init];
item.title = @"半导体照明";
item.selected = NO;
item.order = 5;
[channelArray addObject:item];

item = [[TopMenuItem alloc] init];
item.title = @"电子工程";
item.selected = YES;
item.order = 2;
[channelArray addObject:item];

item = [[TopMenuItem alloc] init];
item.title = @"光通讯";
item.selected = NO;
item.order = 3;
[channelArray addObject:item];

item = [[TopMenuItem alloc] init];
item.title = @"太阳能光伏";
item.selected = YES;
item.order = 4;
[channelArray addObject:item];

NSString *filterString = @"title CONTAINS[cd] ‘光‘";

filterString = @"selected==1";

filterString = @"order BETWEEN {3,5}";

NSPredicate *predicate = [NSPredicate predicateWithFormat:filterString];

NSArray *filteredArray = [channelArray filteredArrayUsingPredicate:predicate];

for (TopMenuItem *item in filteredArray)
{
    NSLog(@"%@",item);
}

Code

时间: 2024-10-08 03:16:18

数组的排序及筛选的相关文章

IOS数组的排序和筛选

1.排序 [self.tableItems sortUsingComparator:^NSComparisonResult(GPBTeacherBrief* obj1, GPBTeacherBrief* obj2) { if (obj1.distanceFromMe < obj2.distanceFromMe) { return NSOrderedAscending; }else if(obj1.distanceFromMe == obj2.distanceFromMe){ return NSO

给object数组进行排序(排序条件是每个元素对象的属性个数)

从汤姆大叔的博客里看到了6个基础题目:本篇是第3题 - 给object数组进行排序(排序条件是每个元素对象的属性个数) 解题关键: 1.Array.sort的用法 2.object的属性数量的统计 解点1:Array.sort的用法 Array.sort可以为数组指定一个排序规则,一般用如下格式进行指定,代码如下: var arr = [10,6,0,4]; console.log( arr.sort() ); //按字符排序 0,10,4,6 console.log( arr.sort( fu

js中的数组对象排序

一.普通数组排序 js中用方法sort()为数组排序.sort()方法有一个可选参数,是用来确定元素顺序的函数.如果这个参数被省略,那么数组中的元素将按照ASCII字符顺序进行排序.如: var arr = ["a", "b", "A", "B"]; arr.sort(); console.log(arr);//["A", "B", "a", "b"

Excel实用知识2(排序,筛选,分析工具)

Excel实用知识2 [排序,筛选,分析工具(描述统计,相关系数,回归分析,抽样分析,预测工作表)] 纯手打,可能有错别字,使用的版本是office2013 转载请注明出处 http://www.cnblogs.com/hnnydxgjj/p/6337670.html ,谢谢 简单排序 简单的降序,升序 降序 升序 条件排序 [数据]--[排序] 会显示当前排序条件,点击“添加条件”,设置新的约束,这适用于多条件排序 自定义排序 [数据]--[排序] 筛选数据 选择要筛选的内容后,[数据]--[

第六讲 Block块语法及Block与数组的排序,ios字面量的使用(源代码上传)

1 #import <Foundation/Foundation.h> 2 3 4 #import "Student.h" 5 6 int c =200; 7 int main(int argc, const char * argv[]) { 8 @autoreleasepool { 9 /* 10 ------------------------------------- 11 定义block变量的四种方法 12 -----------------------------

小康陪你学JAVA--------sort方法对数组进行排序

本篇和大家分享另一种数组的操作的方法——sort方法对数组进行排序. 范例:TestJava4_5.java 01 // 以下程序是数组的排序操作,在这里使用了sort方法对数组进行排序 02 import java.util.*; 03 public class TestJava4_5 04 { 05    public static void main(String[] args) 06  { 07       int a[] = {4,32,45,32,65,32,2} ; 08 09  

根据对象的某一属性对数组进行排序

//根据对象的某个属性对数组进行排序 function compar(attribute){ return function (obj1,obj2){ if(obj1.attribute > obj2.attribute){ return -1; }else{ return 1; } } };

php多维数组自定义排序 uasort()

php内置的排序函数很多:正反各种排: 常用的排序函数: sort() - 以升序对数组排序rsort() - 以降序对数组排序asort() - 根据值,以升序对关联数组进行排序ksort() - 根据键,以升序对关联数组进行排序arsort() - 根据值,以降序对关联数组进行排序krsort() - 根据键,以降序对关联数组进行排序 基本都能满足需求了:关于这些函数的使用方法就不多啰嗦了: 但是在项目的实际开发中还是会有些更加苛刻的排序需求:今天要介绍的排序函数是: uasort() ua

array_multisort—对多个数组或多维数组进行排序

From: http://www.cnblogs.com/lwbqqyumidi/archive/2013/01/31/2887188.html PHP中array_multisort可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序. 关联(string)键名保持不变,但数字键名会被重新索引. 输入数组被当成一个表的列并以行来排序——这类似于 SQL 的 ORDER BY 子句的功能.第一个数组是要排序的主要数组.数组中的行(值)比较为相同的话就按照下一个输入数组中相应值的