简体   繁体   中英

Is there any way to filter an array of dates using predicate for day of the week?

I have an array with custom objects which have a NSDate property. I would like to somehow get all objects whose NSDate are on Sunday, Monday, Tuesday, and so on.

I feel like this isn't possible using predicates but hoping I am wrong and hoping there is a way without having to iterate over all objects, get the dates, convert them using date formatter and then figuring out the day.

I think block method of predicate code will be more feasible to do this task.

Here is my code

    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];

Here Object is my Custom object class which hold two field ie one NSString and one NSDate attribute.

Here is my Object class for your reference

@interface Object : NSObject

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSDate *mDate;

@end

Hope it helps. Please let me know if you face any issue with this approach.

I was able to figure this out. Here's my way in Objective-C which can also be adapted for swift easily I am sure.

I actually have an array of custom objects each of which has a NSDate property which I need to be filtering on by day of week.

I achieved my solution by adding another custom getter to my custom object:

Interface:

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

Implementation:

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

The dayOfWeekFormatter is a NSDateFormatter which I create in my AppDelegate which can be reused instead of recreating it each time:

@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];

You must set the Locale!

Now I am able to use this predicate to filter for whatever day I need. Here's an example for filtering for all objects on Wednesday:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM