1

我有这个模型:

@interface Data : NSObject
@property int Period; 
@property (nonatomic, assign) NSDate *Start;
@property (nonatomic, assign) NSDate *End;
@end

@implementation Data
@synthesize Period, Start, End;
@end

我在可变数组中添加数据。

@property (strong, nonatomic) NSMutableArray* myArray;
self.myArray = [NSMutableArray arrayWithCapacity:0];

Data *element1 =[ [Data alloc] init];
element1.Period = 1;
element1.Start = dateStart1;
element1.End = dateEnd1;
[self.myArray addObject:element1];

Data *element2 =[ [Data alloc] init];
element2.Period = 2;
element2.Start = dateStart2;
element2.End = dateEnd2;
[self.myArray addObject:element2];

Data *element3 =[ [Data alloc] init];
element3.Period = 3;
element3.Start = dateStart3;
element3.End = dateEnd3;
[self.myArray addObject:element3];

我可以从数组中提取开始日期

Data * extractDateStart = [self.myArray valueForKey:@"Start"];
NSLog(@"All Start Dates: %@", extractDateStart);

我需要循环该数组以搜索特定日期(由用户插入)在三个时期中的哪个时期。

我知道如何从“正常”数组中提取数据:

for(NSString * extractDate in self.myArray) {
    NSLog(extractDate);
}

并且也知道如何将一个日期与另一个日期进行比较:

  switch ([dateInserted compare: date]) {
    case NSOrderedAscending:
        // dateInserted old than date
      break;
    case NSOrderedSame:
        // dateInserted the same then date
      break;
    case NSOrderedDescending:
        // dateInserted new then date 
      break;
    default:
        // generic error
      break;
}

但是在这种情况下如何移动?

4

1 回答 1

1

我可能不明白你的问题,但听起来像你:

  • 提供用户NSDate
  • 想要找到落在日期和日期之间的Data对象NSDateStartEnd

如果是这样的话,这样的事情应该可以工作:

NSDate *dateToFind = ...;
Data *foundData = nil; // We will put the correct Data object here if we find it    

for (Data *data in self.myArray) {
    // Test that dateToFind is between data.Start and data.End
    if (([dateToFind compare:data.Start] != NSOrderedAscending) 
            && ([dateToFind compare:data.End] != NSOrderedDescending)))
    {
        foundData = data; // dateToFind is in this Data's date range
    }
}

// foundData is either nil or contains the Data you were looking for

有关测试日期是否介于其他两个日期之间的其他好方法,请参阅此问题

于 2012-12-08T19:47:56.837 回答