检查自定义对象数组是否包含具有特定date的对象

我有一个event objects的数组。 该对象有几个属性。 其中一个属性是NSDate eve_date

现在我想检查该对象数组是否包含某个NSDate d

我正在做以下

 if([[matches valueForKey:@"eve_date"] containsObject:d]){ NSLog(@"contains object"); }else{ NSLog(@"does not contains object"); } 

但是这不起作用。 谁能帮我 ?

亲切的问候

编辑

好吧,让我更清楚。 我正在制作一个日历应用程序。 我提取了特定月份内的所有事件。 我现在需要做的是在正确的date在我的日历上放置一个标记。 所以我有这个function。

 NSLog(@"Delegate Range: %@ %@ %d",start,end,[start daysBetweenDate:end]); self.dataArray = [NSMutableArray array]; self.dataDictionary = [NSMutableDictionary dictionary]; NSDate *d = start; while(YES){ for (Event *event in matches) { if([event.eve_date isEqualToDate:d]){ // (self.dataDictionary)[d] = save event title in here [self.dataArray addObject:@YES]; //place marker on date 'd' }else{ [self.dataArray addObject:@NO]; // don't place marker } } NSDateComponents *info = [d dateComponentsWithTimeZone:calendar.timeZone]; info.day++; d = [NSDate dateWithDateComponents:info]; if([d compare:end]==NSOrderedDescending) break; } 

但是现在我通过我的一系列事件循环了31次(本月的天数)。 (这可能不是最佳实践解决scheme???)

我也觉得问题是这个date的时间是不一样的。 例如:

 eve_date --> 2013-08-13 12:00 d --> 2013-08-13 15:00 

所以我可能应该使用一个NSDateformatter只获取date本身没有时间?

我对么 ?

我不是很熟悉KVC,但是如果解决scheme不需要使用KVC,那么可以迭代:

 NSDate *dateToCompare = ...; BOOL containsObject = NO; for (MyEvent *e in matches) { if ([e.eve_date isEqualToDate:dateToCompare]) { containsObject = YES; break; } } if (containsObject) NSLog(@"Contains Object"); else NSLog(@"Doesn't contain object"); 

我和KVC有过一段戏,并试图解决这个问题。 你只是缺lessvalueForKeyPath而不是valueForKey

 if ([[matches valueForKeyPath:@"eve_date"] containsObject:d]) { NSLog(@"Contains object"); } else { NSLog(@"Does not contain object"); } 

NSDate是一个绝对的时间点。 要检查date是否在某一天 ,您必须将其与“一天的开始”和“第二天的开始”进行比较。

下面的(伪)代码应该certificate这个想法:

 NSDate *start, *end; // your given range NSDate *currentDay = "beginning of" start; // while currentDay < end: while ([currentDay compare:end] == NSOrderedAscending) { NSDate *nextDay = currentDay "plus one day"; for (Event *event in matches) { // if currentDay <= event.eve_date < nextDay: if ([event.eve_date compare:currentDay] != NSOrderedAscending && [event.eve_date compare:nextDay] == NSOrderedAscending) { // ... } } currentDay = nextDay; } 

“一天的开始”可以计算如下:

 NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *aDate = ...; NSDate *beginningOfDay; [cal rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfDay interval:NULL forDate:aDate];