LoginSignup
21
21

More than 5 years have passed since last update.

NSDate の compare 結果を100倍分かりやすくする

Last updated at Posted at 2014-04-15

NSDate の compare: は NSComparisonResult を返すのだが、NSOrderedAscending と NSOrderedDescending はどっちがどっちなのか直感的に分かりにくい。比較演算子ならそうでもないんだけど、Ascending と Descending という単語を解釈するのに時間がかかる。なので最初から別の言葉に置き換えてしまう。

#define WKR_IsEarlier NSOrderedAscending
#define WKR_IsLater NSOrderedDescending

#define WKR_L_IsMorePastThan_R NSOrderedAscending
#define WKR_L_IsMoreFutureThan_R NSOrderedDescending


NSDate* now=[NSDate date];
NSDate* past=[now dateByAddingTimeInterval:-100000];

if ([now compare:past]==WKR_IsLater) {
    NSLog(@"now is later than past");
}

prefix header に書いとくとよいかもしれません。

CMTime を比較するマクロ CMTIME_COMPARE_INLINE をパクってこういうのもかっこいい ( @norio_nomura さんのおかげで思い出せました)。

#define MY_NSDATE_COMPARE_INLINE(date1, comparator, date2) ((BOOL)([date1 compare:date2] comparator 0))

NSLog(@"%d", MY_NSDATE_COMPARE_INLINE(now, <, past)); //NO
NSLog(@"%d", MY_NSDATE_COMPARE_INLINE(now, >, past)); //YES
NSLog(@"%d", MY_NSDATE_COMPARE_INLINE(now, ==, now)); //YES
NSLog(@"%d", MY_NSDATE_COMPARE_INLINE(now, ==, past)); //NO

あ、これもしかして3つ比較できるんじゃね?

#define MY_NSDATE_TRI_COMPARE_INLINE(date1, compA, date2, compB, date3) ((BOOL)(([date1 compare:date2] compA 0) && ([date2 compare:date3] compB 0)))

NSDate* now=[NSDate date];
NSDate* past=[now dateByAddingTimeInterval:-100000];
NSDate* future=[now dateByAddingTimeInterval:100000];

NSLog(@"%d",MY_NSDATE_TRI_COMPARE_INLINE(past, <=, now, <=, future)); //YES
21
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
21