gpt4 book ai didi

ios - NSPredicate 与 NSDate 按天/月过滤但不是年

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:42 27 4
gpt4 key购买 nike

我需要创建一个谓词,它需要使用属性 creationDate 过滤对象列表,这是一个 NSDate 对象。我想获取具有相同日期和月份但不同年份的对象列表。实际上,我想要过去今天(作为日/月)发生的对象。我怎样才能创建这个谓词?例如:今天是 2016 年 7 月 27 日,我想要创建日期为 7 月 27 日的所有对象。

最佳答案

首先,从日期中提取日和月...

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];

接下来,(一种方式)构建谓词...

[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
// object must be cast to the type of object in the list
MyObject *myObject = (MyObject *)object;
NSDate *creationDate = myObject.creationDate;

// do whatever you want here, but this block must return a BOOL
}];

将这些想法放在一起......

- (NSPredicate *)predicateMatchingYearAndMonthInDate:(NSDate *)date {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];

return [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
MyObject *myObject = (MyObject *)object;
NSDate *creationDate = myObject.creationDate;
NSDateComponents *creationComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:creationDate];
NSInteger creationDay = [creationComponents day];
NSInteger creationMonth = [creationComponents month];
return day == creationDay && month == creationMonth;
}];
}

就是这样。使用一些 NSDate 构建谓词,您希望在数组中匹配日期和月份,然后在数组上运行该谓词 (filteredArrayUsingPredicate:)。

NSDate *today = [NSDate date];
NSPredicate *predicate = [self predicateMatchingYearAndMonthInDate:today];
NSArray *objectsCreatedToday = [myArray filteredArrayUsingPredicate:predicate];

关于ios - NSPredicate 与 NSDate 按天/月过滤但不是年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com