【问题标题】:Is there any way to filter an array of dates using predicate for day of the week?有没有办法使用谓词过滤日期数组?
【发布时间】:2018-11-01 05:13:13
【问题描述】:

我有一个包含具有 NSDate 属性的自定义对象的数组。我想以某种方式获取 NSDate 为星期日、星期一、星期二等的所有对象。

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

【问题讨论】:

    标签: ios nsdate nspredicate


    【解决方案1】:

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

    这是我的代码

        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 是我的自定义对象类,它包含两个字段,即一个NSString 和一个NSDate 属性。

    这是我的 Object 类供您参考

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

    希望对您有所帮助。如果您在使用这种方法时遇到任何问题,请告诉我。

    【讨论】:

    • 感谢您的回复!我能够使用我的解决方案解决它,但您的解决方案也有效!再次感谢!
    【解决方案2】:

    我能够弄清楚这一点。这是我在 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'"]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2021-10-22
      • 2021-03-08
      • 2022-12-08
      • 2015-04-07
      相关资源
      最近更新 更多