我打算写一个日期过滤器。
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”的项目。 我的代码不起作用。如何修复?
最佳答案
首先,您需要将 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);
关于iOS:如何使用 NSPredicate 过滤 <string *>Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458782/