2013-08-20 117 views
2

我有一个event objects的数组。该对象有几个属性。其中一个属性是NSDate eve_date检查自定义对象数组是否包含某个日期的对象

现在我要检查,如果对象的数组中含有一定NSDate d

我做了以下

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

但是,这是行不通的。谁能帮我 ?

亲切的问候

编辑

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

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次(天量的关月)。 (这可能不是最佳做法解决方案???)

我也认为问题是,日期的时间是不一样的。例如:

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

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

我正确吗?

+0

你检查(并记录)的'[matches valueForKey:@“eve_date”]'的内容? – Wain

+1

解决方案是否必须使用KVC? –

+0

我可以通过NSPredicate来实现。 –

回答

5

我不是非常好,KVC精通,但如果解决方案不需要使用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并试图解决这个问题。你只缺valueForKeyPath代替valueForKey

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

非常简单直接的解决方案。 +1 –

+0

终于搞定了!你的回答最能帮助我!谢谢 !! – Steaphann

0

NSDate是时间的绝对点。要检查日期是否落在给定的, 上,您必须将其与“一天的开始”和“下一天的开始”进行比较。

以下(伪)代码应表现出的理念是:

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]; 
相关问题