【问题标题】:Iterate over NSArray filled with dates and comparing to another NSArray遍历充满日期的 NSArray 并与另一个 NSArray 进行比较
【发布时间】:2011-08-28 12:42:04
【问题描述】:

我有一个以 NSDate 格式填充大约 30 个日期的 NSArray,

我需要做的是从中创建另一个数组,其中包含从第一个日期到最后一个日期的所有日期的布尔值。

前数组 1 2011 年 1 月 1 日 2011 年 3 月 1 日 2011 年 5 月 1 日

数组 2 是的 不 是的 不 是的

tapku 图书馆日历我需要这个

这是我迄今为止所拥有的,但我从未改变

int i=0;
for (NSDate *date = [[startingDate copy] autorelease]; [date compare: endingDate] < 0;
     date = [date dateByAddingTimeInterval:24 * 60 * 60] ) {
    NSLog( @"%@ in [%@,%@]", date, startingDate, endingDate );

    int day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:[eventDates objectAtIndex:i]];
    int day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSEraCalendarUnit forDate:date];

    if(day1-day2==0) {
        NSLog(@"yeh");
        i=i+1;
        //add yes to array2

    } else {
        NSLog(@"nah");
        NSLog(@"%i",i);
        //add no to array 2
    }
}

【问题讨论】:

    标签: iphone objective-c for-loop nsdate


    【解决方案1】:

    我想我不太明白你想做什么,但我会试一试。

    假设您有 2 个NSDate,分别称为date1date2,并且您想标记NSDate 数组中的任何条目,称为arrayOfDates,它们位于2 NSDate's,或者没有,并将 YESNO 值存储在另一个数组中,称之为 boolValuesOfDates。那就试试这个方法:

    - (void)compareDatesOfArrayFromDate:(NSDate *)date1 toDate:(NSDate *)date2; {
    
      NSDate * firstDate;
      NSDate * secondDate;
    
      if([date1 timeIntervalSinceDate:date2] >= 0){
        firstDate = date2;
        secondDate = date1;
      }
      else{
        firstDate = date1;
        secondDate = date2;
      }
    
      if(boolValuesOfDates != nil)
        [boolValuesOfDates release]; // Release the YES/NO array for the new values.
    
      boolValuesOfDates = [[NSMutableArray alloc] initWithCapacity:[arrayOfDates count]];
    
      BOOL isInbetweenDates;
      NSDate * curDate;
    
      for(int i = 0; i < [arrayOfDates count]; i++){
        curDate = [arrayOfDates objectAtIndex:i];
        isInbetweenDates = NO;
        if([curDate timeIntervalSinceDate:firstDate] >= 0){
          if([curDate timeIntervalSinceDate:secondDate] <= 0){
            isInbetweenDates = YES;
          }
        }
        [boolValuesOfDates addObject:[NSNumber numberWithBool:isInbetweenDates]];
      }
    }
    

    此方法检查输入的2个NSDate的顺序,然后比较数组中的NSDate,如果它们介于两者之间,则用YESNO标记它们否则。希望有帮助!

    【讨论】:

    • 这正是我想要的非常感谢,但似乎给了我一个越界异常
    • 如果您发布实际错误,帮助您会更容易。另外,不要忘记接受答案,以便其他人知道这是对以后的帮助。
    • 我放弃了这种方法并决定尝试不同的方法,但现在又出现了另一个问题! link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多