代码之家  ›  专栏  ›  技术社区  ›  user6631314

IOS/Objective-C:n在Objective-C中可能没有处理程序的计时器?

  •  -2
  • user6631314  · 技术社区  · 6 年前

    我正在尝试将一些使用attimer的Swift输入到Objective-C中。

        func type(string: String) {
            var wordArray  = ["Sox Win", "Verlander To Start", "Race Tightens"] // an array of strings
            var wordIndex = 0
            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
                self.textview.text.append(wordsArray[wordIndex])
                wordIndex += 1
                if wordIndex == wordArray.count {
                    timer.invalidate()
                }
            }
        }
    }
    

    但是,在Objective-C中,您通常会看到:

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                          target: self
                          selector:@selector(update:)
                          userInfo: nil repeats:YES];
    -(void) update:(NSTimer*)timer
    {
    int i=0;i<4;i++ {
    NSLog(@"another second");
    }
    timer.invalidate;
    timer = nil;
    }
    

    使用这个处理程序,我不知道如何迭代数组中的单词,而不反复创建数组,这显然不起作用。

    - (void)updateView:(NSTimer *)timer
    {
    NSArray*items =@[@"item1", @"item2", @"item3", @"item4", @"item5"];
     for(int i=0;i<[items count];i++){
        self.textView.text = [self.textView.text stringByAppendingString:items[i]];
        if (i == [items count]) {
            [self.timer invalidate];
            self.timer = nil;
        }
        }
    }
    

    我应该用userInfo做些什么吗?或者我如何利用时间一次更新一个单词?提前谢谢你的建议。

    1 回复  |  直到 6 年前
        1
  •  2
  •   rmaddy    6 年前

    Objective-C支持相同的基于块的 NSTimer

    - (void)type:(NSString *)string {
        NSArray *wordArray = @[ @"Sox Win", @"Verlander To Start", @"Race Tightens" ];
        __block NSInteger wordIndex = 0;
        [NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            // append wordsArray[wordIndex]
            wordIndex += 1;
            if (wordIndex == wordArray.count) {
                [timer invalidate];
            }
        }];
    }
    

    dispatch_after :

    - (void)type:(NSString *)string {
        NSArray *wordArray = @[ @"Sox Win", @"Verlander To Start", @"Race Tightens" ];
    
        for (NSInteger i = 0; i < wordArray.count; i++) {
            dispatch_after(i + 0.1, dispatch_get_main_queue(), ^{
                // append wordsArray[i]
            });
        }
    }