我知道有一种名为NSTimeInterval
的数据类型,但这是以秒为单位的。我想要一个能够表示时间范围的对象表示,例如 6 月 21 日星期四 8:00 - 6 月 21 日星期四 9:00。稍后我想比较当前日期/时间并检查它是否适合这个范围。最好的方法是什么?
最佳答案
我建议使用两个 NSDate 对象来存储开始日期和结束日期。您可以使用 timeIntervalSinceDate:
方法轻松确定它们之间是否存在日期:
- (BOOL)dateInInterval:(NSDate *)testDate {
// date1 is the instance variable containing the starting date
// date2 is the instance variable containing the ending date
return ([testDate timeIntervalSinceDate:date1] > 0 &&
[testDate timeIntervalSinceDate:date2] < 0);
}
您只需要创建一个包含两个 NSDate 对象的类,确保第一个位于第二个之前,并包含此方法。
仅供引用,NSTimeInterval 不是一个类,它是 double 的 typedef。
编辑
由于您想使用它们作为字典的键,因此您可以使用与此类似的内容来存储和搜索数据:
@protocol IntervalDictionaryKey <NSObject>
// The class you use as keys for your dictionary must implement this method to determine if a object is in the interval
- (BOOL)intervalContains:(id)object;
@end
@interface IntervalDictionary : NSObject {
NSMutableArray *keys, *values;
}
- (void)addInterval:(id<IntervalDictionaryKey>)interval withObject:(id)object;
- (void)setObject:(id)object forIntervalOf:(id)intervalObject;
- (id)objectForIntervalOf:(id)object;
@end
@implementation IntervalDictionary
- (id)init {
if(self = [super init]) {
keys = [NSMutableArray new];
values = [NSMutableArray new];
}
return self;
}
- (void)dealloc {
[keys release];
[values release];
[super dealloc];
}
- (void)addInterval:(id<IntervalDictionaryKey>)interval withObject:(id)object {
[keys addObject:interval];
[values addObject:object];
}
- (void)setObject:(id)object forIntervalOf:(id)intervalObject {
id<IntervalDictionaryKey> key;
NSUInteger i = 0;
for(key in keys) {
if([key intervalContains:intervalObject]) {
[values replaceObjectAtIndex:i withObject:object];
break;
}
++i;
}
}
- (id)objectForIntervalOf:(id)object {
id<IntervalDictionaryKey> key;
NSUInteger i = 0;
for(key in keys) {
if([key intervalContains:object]) {
return [values objectAtIndex:i];
}
++i;
}
}
@end
用法:
间隔类别示例:
@interface DateInterval : NSObject <IntervalDictionaryKey> {
NSDate *date1, *date2;
}
- (BOOL)intervalContains:(NSDate *)date; // this is the same as the dateInInterval method above
@end
@implementation DateInterval
// initializer which sets date1 and date2
- (BOOL)intervalContains:(NSDate *)date {
return ([date timeIntervalSinceDate:date1] > 0 &&
[date timeIntervalSinceDate:date2] < 0);
}
@end
使用代码示例:
//intervalX is a DateInterval object, created elsewhere
//objectX is any object, created elsewhere
//objectInX is a NSDate which is part of intervalX, created elsewhere
IntervalDictionary *dict = [IntervalDictionary new];
[dict addInterval:interval0 withObject:object0];
[dict addInterval:interval1 withObject:object1];
[dict objectForIntervalOf:objectIn0]; // returns object0
[dict objectForIntervalOf:objectIn1]; // returns object1
[dict setObject:object2 forIntervalOf:objectIn1]; // changes the object for interval1 to object2
[dict objectForIntervalOf:objectIn1]; // now returns object2
关于iphone - 表示 Objective-C 中的时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5446738/