【问题标题】:NSDate calling a methodNSDate 调用方法
【发布时间】:2014-08-26 19:19:32
【问题描述】:

我是编码新手,请见谅!

背景:

我有一个带有简单标签的应用程序,它以天、小时、分钟和秒为单位倒计时到给定日期。 我使用NSDateNSTimers 做到了这一点:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //Countdown timer
    destinationDate = [NSDate dateWithTimeIntervalSince1970:1413961418];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

-(void)updateLabel {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int units = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];

    [countdownLabel setText:[NSString stringWithFormat:@"%ld%c : %ld%c : %ld%c : %ld%c", (long)[components day], 'd', (long)[components hour], 'h', (long)[components minute], 'm', (long)[components second], 's']];
}

问题:

当倒计时标签达到 0 时(即当我们到达给定日期时)我怎样才能获得触发方法,例如隐藏对象?

【问题讨论】:

  • 旁注 - 为什么在格式字符串中使用 %c 表示 hm 等?只需像冒号一样将字母放在格式字符串中。

标签: objective-c cocoa-touch nsdate nstimer


【解决方案1】:

也许我不明白您的问题,但您能否验证标签文本是否等于“0:0:0 h.s”之类的内容?

我的意思是,你已经有了 updateLabel 方法。

【讨论】:

  • 是的,标签等于到给定日期的倒计时,所以它表示类似 180 天 10 小时 30 分钟 2 秒,然后每秒倒计时。
【解决方案2】:

最好的方法是查看当前日期是否晚于或等于destinationDate

if ([destinationDate timeIntervalSinceNow] <= 0) {
    // The destination date is in the past - do something
}

【讨论】:

    【解决方案3】:

    如果您想要条件检查倒数计时器是否达到零,请尝试以下条件:-

         if ([destinationDate compare:[NSDate 
        date]]==NSOrderedSame)
    
         //hiding your object
         }
    

    【讨论】:

    • 这行不通。日期以毫秒为单位存储。两者完全相等的机会基本上为零。
    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2014-08-13
    • 2011-08-30
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多