iphone – NStimer在iOS中无法正常工作

我正在使用以下代码显示时间…我在viewController中有滚动视图…这里我显示的时间从00:00.00开始(mm:ss:SS)(分钟:秒:毫秒)并且目标是递增毫秒,秒基于毫秒,基于秒的分钟…但我想显示从75:00.00(mm:ss:SS)开始的时间,我想将毫秒,秒和分钟减少到00:00.00(mm:ss) .SS)……我怎么能……?

我已经在SO中通过以下链接询问了这个… NSTimer Decrease the time by seconds/milliseconds

我按照那段代码时间不计算(在后台也是)当我拖动并按住滚动视图而不释放鼠标点击…帮我修改下面的代码…

enter code here
@interface ViewController : UIViewController
{
    IBOutlet UILabel *time;
    NSTimer *stopWatchTimer;
    NSDate *startDate;
    NSTimeInterval secondsAlreadyRun;
}

- (void)reset:(id)sender;
- (void)onStartPressed:(id)sender; 
- (void)onStopPressed:(id)sender;


enter code here
-(void)showActivity:(NSTimer *)tim 
{
    NSDate *currentDate = [NSDate date];

    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    // Add the saved interval
    timeInterval += secondsAlreadyRun;
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    static NSDateFormatter * dateFormatter = nil;
    if( !dateFormatter ){
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"mm:ss.SS"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    }
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    time.text = timeString;

    //    [dateFormatter release];
}

- (void)onStartPressed:(id)sender 
{
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10 
                                                      target:self 
                                                    selector:@selector(showActivity:) 
                                                    userInfo:nil 
                                                     repeats:YES];
    // Save the new start date every time
    startDate = [[NSDate alloc] init]; // equivalent to [[NSDate date] retain];
    [stopWatchTimer fire];
}

- (void)onStopPressed:(id)sender
{
    // _Increment_ secondsAlreadyRun to allow for multiple pauses and restarts
    secondsAlreadyRun += [[NSDate date] timeIntervalSinceDate:startDate];
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;

    //    [startDate release];
    //    [self showActivity:stopWatchTimer];
}
最佳答案
您必须注册计时器才能在NSRunLoopCommonModes中运行

stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10 
                                                  target:self 
                                                selector:@selector(showActivity:) 
                                                userInfo:nil 
                                                 repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:stopWatchTimer forMode:NSRunLoopCommonModes]; 

转载注明原文:iphone – NStimer在iOS中无法正常工作 - 代码日志