2013-05-18 56 views
1

這timmer在我的所有設備(5,Ipad和兩個4S)上效果很好,但它似乎不適用於我擁有的兩個3GS。由於某種原因,3秒鐘的時間真的很慢。 繼承人視頻說明問題:隨着時間的交易非常有趣的不同設備上的時間差異

http://youtu.be/4vdusgnIXcs

而且繼承人的代碼:

- (void)showTime 
{ 
    int hours = 0; 
    int minutes = 0; 
    int seconds = 0; 
    int hundredths = 0; 
    NSArray *timeArray = [NSArray arrayWithObjects:self.hun.text, self.sec.text, self.min.text, self.hr.text, nil]; 
    for (int i = [timeArray count] - 1; i >= 0; i--) { 
     int timeComponent = [[timeArray objectAtIndex:i] intValue]; 
     switch (i) { 
      case 3: 
       hours = timeComponent; 
       break; 
      case 2: 
       minutes = timeComponent; 
       break; 
      case 1: 
       seconds = timeComponent; 
       break; 
      case 0: 
       hundredths = timeComponent; 
       hundredths++; 
       score++; 
       break; 

      default: 
       break; 
     } 

    } 
    if (hundredths == 100) { 
     seconds++; 
     hundredths = 0; 
    } 
    else if (seconds == 60) { 
     minutes++; 
     seconds = 0; 
    } 
    else if (minutes == 60) { 
     hours++; 
     minutes = 0; 
    } 
    self.hr.text = [NSString stringWithFormat:@"%.0d", hours]; 
    self.min.text = [NSString stringWithFormat:@"%.2d", minutes]; 
    self.sec.text = [NSString stringWithFormat:@"%.2d", seconds]; 
    self.hun.text = [NSString stringWithFormat:@"%.2d", hundredths]; 

    scoreLabel.text= [NSString stringWithFormat:@"%i",score]; 

請幫我揣摩什麼怎麼回事。它在我需要做的事情上丟失的新設備上運行良好。

預先感謝您!

回答

1

如果我正確理解你的代碼,你每秒運行一次NSTimer 100次。

如果這是正確的,您可能主要有設計問題,而不是性能或NSTimer問題。

NSTimer不能保證按時運行。唯一保證的是,它不會提前運行它應該是。

既然你不知道計時器方法何時運行,你不能相信它會每秒運行100次。這意味着計時器是「計數」時間的不好方法。更好的方法是在啓動計時器時節省系統時間,並且當您想知道已經用了多少時間時,可以使用當前系統時間並減去開始時間。 NSTimer只能用於顯示目的。

事情是這樣的:

// instance variables: 
NSDate *startDate; 
NSTimer *timer; 

- (void)startTimer { 
    [timer invalidate]; 
    startDate = [NSDate date];  // save current time 

    timer = [NSTimer timerWithTimeInterval:0.075 target:self selector:@selector(displayTime:) userInfo:nil repeats:YES]; 
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 
} 


- (void)displayTime:(NSTimer *)timer { 
    // the timer method is for display only. it doesn't "count" time 

    // calculate elapsed time from start time 
    NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate]; 

    NSInteger ti = (NSInteger)elapsedTime; 

    // convert elapsed time (in seconds) into hours, minutes, seconds ... 
    double fractionalSeconds = fmod(elapsedTime, 1); 
    NSInteger hundreds = fractionalSeconds * 100; 
    NSInteger seconds = ti % 60; 
    NSInteger minutes = (ti/60) % 60; 
    NSInteger hours = (ti/3600); 

    NSLog(@"%02d:%02d:%02d.%02d", hours, minutes, seconds, hundreds); 
} 
+0

謝謝。我會試試看看它是如何工作的! – aasatt

0

使用這兩種設備和比較來分析您的程序與Instruments.app。由於您已經在演示中隔離了問題,因此它生成的報告應該很快顯示執行時間差異。一旦你瞭解了最大的問題領域,你就會知道你可以改變哪些程序部分,以使其運行得更快。然後將您的更新與初始運行進行比較,以瞭解速度如何提高。根據需要重複。

相關問題