Good night, I try to print text to the label character by character, I do it in a separate thread, but why does the text appear in the label all at once, rather than character by character, please tell me how to do it right or what to fix? I create a stream like this:

[NSThread detachNewThreadSelector:@selector (TestMethod) toTarget:self withObject:nil]; -(void) TestMethod { NSString *s = textplace.text; int i = textplace.text.length; label1.text = @""; for(int j =0;j < i;j++) { NSRange range = NSMakeRange(j, 1); label1.text = [label1.text stringByAppendingString:[s substringWithRange:range]]; [NSThread sleepForTimeInterval:1]; } [NSThread exit]; 

}

  • Try increasing the interval: NSThread sleepForTimeInterval: 1000] It seems to me that microseconds are indicated there, not seconds. - uzumaxy
  • NSTimeInterval is always in seconds - iFreeman

1 answer 1

You can not do anything with the UI being not in the MainThread, remember this, this may cause incorrect work or even crashes. Try being in Main Thread

 [self.label performSelector:@selector(setText:) withObject:newText afterDelay:5.0]; 

I will update the answer to make it clearer:

 for (int i = 0; i < newText.length; i++) { [self.label performSelector:@selector(setText:) withObject:[newText substringToIndex:i] afterDelay:i*2.0]; } 
  • Thanks for the moment with the UI, but unfortunately your version gives the same result as mine, for (int i = 0; i <4; i ++) {[label1 performSelector: @selector (setText :) withObject: [NSString stringWithFormat: @ "% i", i] afterDelay: 2.0]; } will immediately issue 3 in the label, not 1,2,3 in turn, as we would like - Beginnerrr
  • correct because the loop is very fast. Try somewhere for (int i = 0; i <4; i ++) {[label1 performSelector: @selector (setText :) withObject: [NSString stringWithFormat: @ "% i", i] afterDelay: (i * 2)] ; } - KoVadim
  • Thank you! So it works, but you can clarify why if you specify how you did it will work, and if for example for (int i = 0; i <4; i ++) {[label1 performSelector: @selector (setText :) withObject: [ NSString stringWithFormat: @ "% i", i] afterDelay: 5.0]; } then in 5 seconds my troika will appear again immediately and in your version everything is as it should, what kind of magic?) After all, in fact, you simply set the time for a variable, and I immediately became a constant. - Beginnerrr
  • you need to increase the interval, i * 2 at each step of the cycle will be more, respectively, you deferfully run the setText method: 4 times with delays of 0, 2, 4, 6 seconds, hence this effect. In your case, you call setText 4 times: in 2 seconds - iFreeman
  • Thank you so much! What you need! - Beginnerrr