NSDate/NSCalendar 问题

Posted

技术标签:

【中文标题】NSDate/NSCalendar 问题【英文标题】:NSDate/NSCalendar Issue 【发布时间】:2010-08-23 20:56:19 【问题描述】:

我的应用中有以下代码。它是一款 iPad 应用程序,在一个名为 monTable、tueTable 等的单个视图中有五个表格。这些表格代表星期一到星期五。

在这段代码中,我获取日期并将每个表格标题设置为星期一到星期五(本周)的日期。然后,如果我按下按钮 nextWeek 变为 TRUE 并重新加载表数据。这意味着周数增加。看到了吗?

-(IBAction)nextWeekDown
    nextWeek = TRUE;
    [monTable reloadData];


- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section

    curDate = [NSDate date]; // Get current date
    calendar = [NSCalendar currentCalendar];// Init calendar
    comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

    // Week days change from 1 to 7, Sunday is the 1st, Saturday - the last one.
    if (tableView == monTable)
        if(nextWeek == TRUE)
            [comps setHour:168];
            NSDate *date = [calendar dateByAddingComponents:comps toDate:curDate options:0];
        
        else
            [comps setWeekday:2];
        
    
    if (tableView == tueTable)
        if(nextWeek == TRUE)
            [comps setHour:168];
            NSDate *date = [calendar dateByAddingComponents:comps toDate:curDate options:0];
        
        else
            [comps setWeekday:3];
        
    
    if (tableView == wedTable)
        if(nextWeek == TRUE)
            [comps setHour:168];
            NSDate *date = [calendar dateByAddingComponents:comps toDate:curDate options:0];
        
        else
            [comps setWeekday:4];
        
    
    if (tableView == thuTable)
        if(nextWeek == TRUE)
            [comps setHour:168];
            NSDate *date = [calendar dateByAddingComponents:comps toDate:curDate options:0];
        
        else
            [comps setWeekday:5];
        
    
    if (tableView == friTable)
        if(nextWeek == TRUE)
            [comps setHour:168];
            NSDate *date = [calendar dateByAddingComponents:comps toDate:curDate options:0];
        
        else
            [comps setWeekday:6];
        
    

    NSDate *tDate = [calendar dateFromComponents:comps];
    NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"EEE, MMM d"];

    return [formatter stringFromDate:tDate];

我的问题是,由于某种有线原因,星期一到下周只增加了 7 天,而当按下按钮时,其他日子都没有改变有什么想法吗?谢谢。

【问题讨论】:

【参考方案1】:

在 nextWeekDown 方法中,您只重新加载 monTable - 因此其他表自然不会重新加载。您还需要重新加载所有其他表...

【讨论】:

你现在让我看起来很愚蠢... :) 我发誓再也不会在深夜半睡半醒的时候问这样的问题。猜猜这也是学习高效地回读我自己的代码的一部分,我有一天会到达那里。 只是对这个问题的跟进。我有它,所以当按下按钮时 nextWeek 是 TRUE,这意味着表格当然会提前 7 天重新加载。但就我的生活而言,我无法让 nextWeek to = FALSE 并且能够再次按下按钮。 别担心修复了!然而另一个问题!当我按下下周按钮时,它会持续数周,但当它到达 9 月底时,它会回到 8 月。

以上是关于NSDate/NSCalendar 问题的主要内容,如果未能解决你的问题,请参考以下文章

如何计算当前月/年的天数

两个本地通知错误

设置 UILocalNotification 的 fireDate

每天 5 条本地通知

什么是问题管理

SVM原问题与对偶问题