2013-05-18 47 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。由于您已经在演示中隔离了问题,因此它生成的报告应该很快显示执行时间差异。一旦你了解了最大的问题领域,你就会知道你可以改变哪些程序部分,以使其运行得更快。然后将您的更新与初始运行进行比较,以了解速度如何提高。根据需要重复。

相关问题