iOS:如何使用NSPredicate过滤<string *> Array

时间:2019-06-05 10:33:47

标签: ios arrays objective-c

我打算写一个日期过滤器。

 NSMutableArray *muarray  = @[
                        @"2019/6",
                        @"2019/5",
                        @"2019/4",
                        @"2019/3",
                        @"2019/2",
                        @"2019/1",
                        @"2018/12",
                        @"2018/11",
                        @"2018/10",
                        @"2018/9",
                        @"2018/8",
                        @"2018/7",
                        @"2018/6",
                        @"2018/5",
                        @"2018/4",
                        @"2018/3",
                        @"2018/2",
                        @"2018/1",
                        @"2017/12",
                        @"2017/11",
                        @"2017/10",
                        @"2017/9",
                        @"2017/8",
                        @"2017/7",
                        @"2017/6",
                       @"2017/5",
                       @"2017/4",
                        @"2017/3",
                        @"2017/2",
                        @"2017/1"
                         ].mutableCopy;

    NSString *tempStr = [NSString stringWithFormat:@"self between {\'%@\',\'%@\'}", @"2017/8", @"2018/8"];

     NSPredicate *predicate = [NSPredicate predicateWithFormat:tempStr];

   [muarray filterUsingPredicate:predicate];

我想将项目从“ 2017/8”过滤到“ 2018/8”。 我的代码不起作用。如何解决?

1 个答案:

答案 0 :(得分:0)

首先,您需要将NSString的数组转换为NSDate的数组才能使用NSDate进行过滤。请使用下面的代码来满足您的要求。

代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM"];

NSMutableArray *muarray  = @[
                             @"2019/6",@"2019/5",@"2019/4",@"2019/3",@"2019/2",@"2019/1",@"2018/12",@"2018/11",@"2018/10",@"2018/9",@"2018/8",@"2018/7",@"2018/6",@"2018/5",@"2018/4",@"2018/3",@"2018/2",@"2018/1",@"2017/12",@"2017/11",@"2017/10",@"2017/9",@"2017/8",@"2017/7",@"2017/6",@"2017/5",@"2017/4",@"2017/3",@"2017/2",@"2017/1"
                             ].mutableCopy;

NSMutableArray* aryDates = [NSMutableArray new];
for (NSString* strDate in muarray) {
    NSDate *dateFromString = [dateFormatter dateFromString:strDate];
    [aryDates addObject:dateFromString];
}
NSDate* date1 = [dateFormatter dateFromString:@"2017/8"];
NSDate* date2 = [dateFormatter dateFromString:@"2018/8"];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BETWEEN %@", [NSArray arrayWithObjects:date1, date2, nil]];
[aryDates filterUsingPredicate:predicate];
NSLog(@"%@",aryDates);