是否有任何方法可以使用一周中某一天的谓词来筛选日期数组



我有一个带有自定义对象的数组,该数组具有NSDate属性。我想以某种方式获取NSDate在周日、周一、周二等日期的所有对象。

我觉得使用谓词是不可能的,但希望我错了,希望有一种方法不必迭代所有对象,获取日期,使用日期格式器转换它们,然后计算日期。

我认为谓词代码的块方法更可行。

这是我的代码

NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(Object * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:evaluatedObject.mDate];
NSInteger weekDay = [comp weekday]; // 1 = Sunday, 2 = Monday, etc.
return weekDay == 4;
}];
NSArray *arrFilteredObject = [arrData filteredArrayUsingPredicate:pred];

这里Object是我的Custom对象类,它包含两个字段,即一个NSString和一个NSDate属性。

这是我的对象类,供您参考

@interface Object : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSDate *mDate;
@end

希望能有所帮助。如果您对这种方法有任何问题,请告诉我。

我能够弄清楚这一点。这是我在Objective-C中的方法,我相信它也可以很容易地适应swift。

实际上,我有一个自定义对象数组,每个对象都有一个NSDate属性,我需要在一周中的某一天对其进行筛选。

我通过在我的自定义对象中添加另一个自定义getter来实现我的解决方案:

接口:

@property (nonatomic, retain, getter = dayOfWeek) NSString *dayOfWeek;

实施:

-(NSString*)dayOfWeek{
return [[(AppDelegate*)[[UIApplication sharedApplication] delegate] dayOfWeekFormatter] stringFromDate:self.createdAt];
}

dayOfWeekFormatter是我在AppDelegate中创建的NSDateFormatter,它可以重复使用,而不是每次都重新创建:

@property (strong, nonatomic) NSDateFormatter *dayOfWeekFormatter;

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
self.dayOfWeekFormatter = [NSDateFormatter new];
[self.dayOfWeekFormatter setDateFormat:@"eeee"];
[self.dayOfWeekFormatter setLocale:locale];

您必须设置区域设置

现在我可以使用这个谓词来过滤我需要的任何一天。下面是一个星期三过滤所有对象的例子:

NSArray *dayArray = [myTestArrayOfObjects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"dayOfWeek == 'Wednesday'"]];

最新更新