如何在循环迭代中创建间隔

时间:2013-04-18 12:56:24

标签: ios objective-c nstimer

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

我想到了计时器^但我认为这也是错误的想法

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

和选择器

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

在这种情况下,我会每隔5秒钟发一次。

我需要

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

它必须看起来像

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

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分: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;
}

答案 2 :(得分: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];
    });
}