像在Ruby中一样创建一个NSDates数组

Enc*_*PTL 1 objective-c nsdate

我想从今天到下个月创建一系列NSDates.这可以在Ruby中轻松完成Time.now..(Time.now + 30.days)

如何在Objective C中创建一个日期数组,就像在Ruby中一样?

Jos*_*ell 5

遗憾的是,任何ObjC解决方案都比Ruby代码更加冗长.

正确的计算方法是NSDateComponents:

NSMutableArray * dateArray = [NSMutableArray array];
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * plusDays = [NSDateComponents new];
NSDate * now = [NSDate date];
for( NSUInteger day = 0; day < NUMDAYS; day++ ){
    [plusDays setDay:day];
    [dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]];
}
Run Code Online (Sandbox Code Playgroud)

为了使程序更方便(如果你需要做多几次就更多),你可以把这个循环变成一个分类方法NSCalendar,与NUMDAYS使用参数取代,而代以selfcal.