1

我希望我的循环以一(二/n)秒的间隔执行每次迭代。我该怎么做?我尝试使用sleep (5),但我认为这是错误的决定。

我考虑过计时器^,但我认为这也是错误的想法

self.syncTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f
                                                target:self
                                              selector:@selector(serverSync)
                                              userInfo:nil
                                               repeats:YES];

和选择器

-(void) serverSync {
 NSLog (@"Hello");
}

在这种情况下,我将每 5 秒打一次 Hello。

我需要

for (int i = 0; i < Array.count; i ++) {
   NSLog (@"Hello - %d", i);
   some code;
}

它必须看起来像

  • 00.00 你好 - 0
  • 00.05 你好 - 1
  • 00.10 你好 - 2
4

3 回答 3

1

你可以使用这样的东西:

int count;

self.syncTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f
                                                target:self
                                              selector:@selector(nextHello)
                                              userInfo:nil
                                               repeats:YES];

-(void)nextHello {
   if (count < 999) {
      NSLog (@"Hello - %d", count);
      some code;
      count++;
   } else {
      [self.syncTimer invalidate]; //Stop Timer
   }
}

或者,如果您不想使用 NSTimer,您可以使用performSelector afterDelay. 像这样:

[self performSelector:@selector(nextHello:) withObject:[NSNumber numberWithInt:0]; //Start the Cycle somewhere

-(void)nextHello:(NSNumber*)count {
   NSLog (@"Hello - %@", count);
   Some Code
   [self performSelector:@selector(nextHello:) withObject:[NSNumber numberWithInt:[count intValue]+1] afterDelay:5.0];
}
于 2013-04-18T13:08:40.510 回答
0

这是您在 C 中延迟时间的方式:

#include <STDIO.H>
#include <TIME.H>

int main()
{
    int i;
    for(i = 10; i >= 0; i--)
    {
        printf("%i\n",i); // Write the current 'countdown' number
        sleep(1); // Wait a second
    }
    return 0;
}
于 2013-04-18T13:02:41.657 回答
0

你也可以使用这样的东西(但它不像使用 NSTimer 那样清楚)

- (void)sayHello {
    __block NSInteger iteration = 0;
    [self execute:^{
        NSLog(@"Hello: %d", iteration);
        iteration++;
    }
        withCount:5
            delay:0.2];
}

- (void)execute:(void(^)(void))executor repeatCount:(NSInteger)count delay:(NSTimeInterval)delayInSeconds{
    if (count == 0) {
        return;
    };

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^{
        executor();
        [self execute:executor withCount:count - 1 delay:delayInSeconds];
    });
}
于 2013-04-18T13:31:45.580 回答