0

次のコードをコンパイルしましたが、明らかな実行時エラーはありません。ただし、実行すると、表示が 00:00:01 でフリーズします。秒属性のみを表示すると機能します。このコードで見逃した明らかな見落としを誰かが見ていますか? スタートボタンでメモリリークの可能性があることはわかっていますが、最終的には修正します。

前もって感謝します。

#import "StopwatchViewController.h"

@implementation StopwatchViewController

- (IBAction)start{

    //creates and fires timer every second
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
    [myTimer invalidate];
    myTimer = nil;
}

- (IBAction)reset{

    [myTimer invalidate];
    time.text = @"00:00:00";
}

(void)showTime{

    int currentTime = [time.text intValue];

    int new = currentTime +1;

    int secs  = new;
    int mins  = (secs/60) % 60;
    int hours = (mins/60);

    time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours, mins, secs];
}
4

2 に答える 2

3

から 0 を取得しています

int currentTime = [time.text intValue];

にある文字列のためtext

@"00:00:00"

は に変換できないintため、タイマーが起動するたびに 0 に 1 を足して 1 を取得し、それを表示します。とにかく、分と秒は「base-60」であるため、計算は不正確になります* --合計秒数を再度取得するには、時間/分/秒を区切るために実行する計算の逆を行う必要があります。currentTimeivar を作成し、合計秒数を保持することができます。


*実際にはそう呼ばれていません。確かに特定の言葉があると思います。

于 2011-05-13T23:38:03.220 に答える
2
- (IBAction)start{

    currentTime = 0;

    //creates and fires timer every second
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}

- (IBAction)stop{
    [myTimer invalidate];
    myTimer = nil;
}

- (IBAction)reset{

    [myTimer invalidate];
    time.text = @"00:00:00";
}

- (void)showTime{

    currentTime++;

    int secs = currentTime % 60;
    int mins = (currentTime / 60) % 60;
    int hour = (currentTime / 3600);


    time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hour, mins, secs];

}
于 2011-05-16T02:32:17.450 に答える