2013-08-20 118 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]; 
相關問題