ios - 从日期数组获取包含当前日期的日期数组时出错

标签 ios nsarray nsdate nspredicate

我有一个带有 NSDate 对象的 NSMutableArray“NewDate”

(
"2013-08-11 20:26:11 +0000",
"2013-08-11 20:26:11 +0000",
"2013-08-12 06:22:38 +0000",
"2013-08-12 07:24:14 +0000",
"2013-08-12 08:04:05 +0000"
)

我想用今天日期(8 月 12 日)的对象从此数组创建一个新数组

我的代码:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *firstDate = [calendar dateFromComponents:components];
[components setMonth:0];
[components setDay:1];
[components setYear:0];
NSDate *secondDate = [calendar dateByAddingComponents:components toDate:firstDate options:0];

NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];

NSMutableArray *results = [newDate filteredArrayUsingPredicate:predicate];
NSLog(@"%@",result);

但是在创建“结果”时它给了我错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDate 0x72a0ee0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key startDate.'

我做错了什么? 感谢您的帮助。

最佳答案

尝试使用以下代码。

数组={"2013-08-11 20:26:11 +0000", “2013-08-11 20:26:11 +0000”, “2013-08-12 06:22:38 +0000”, “2013-08-12 07:24:14 +0000”, "2013-08-12 08:04:05 +0000"};/////示例。

NSMutableArray *newArray=[[NSMutableArray alloc]init];
NSDate *today=[NSDate date];

NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending

for(int i=0;i<array.count;i++)
{
result = [today compare:[array objectAtIndex:i]];


if(result==NSOrderedDescending)//////If matches with today's date.
{
   [newArray addObject:[array objectAtIndex:i]];
}
}

关于ios - 从日期数组获取包含当前日期的日期数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18184032/

相关文章:

iphone - 如何将字符串转换为日期?

iphone - 如何获取 NSString 中的 NSData 值

ios - 从 SwiftUI View 调用本地 UIViewController 函数

php - 如何通过 PHP 从 NSURLRequest/NSURLConnections (由 iDevices 发送)获取 iDevices 的序列号

iphone - 联系苹果进行一次性(每年)加速审查

iphone - 如何通过数组计数对嵌套NSArray的NSArray进行排序?

cocoa - predicateWithFormat 与 stringWithFormat : is the former supposed to do the same as the latter?

iphone - 我如何在带有 CGGradient 的 NSArray 中舒适地使用 CGColor

objective-c - 计算两个日期之间的白天时间和夜间时间

ios - ImageView 仅在启动屏幕中显示背景颜色