I want to update the contents of this UITextView with this NSMutable array by adding some delay to it.
- (void)viewDidLoad{
[super viewDidLoad];
myArray = [[NSMutableArray alloc]initWithObjects:@"String1",@"String2",@"String3",@"String4", @"String5",..... nil];
int index = arc4random() % [myArray count];
myTextView.text = [myArray objectAtIndex:index];
I want to display this NSMutable array one after other with some delay in UITextView.
Is there some way to display array in UITextView with some delay.
Please help
Why you should use a timer
The correct way of doing this would be to use a repeating timer. The timer is configured to repeat and call a certain method every second.
Inside your (new)
updateTextmethod you would generate the random number and update the text.This is a clean solution that is almost self documenting.
Why you shouldn’t loop and perform after delay.
It is true that you could do this with
performSelector:withObject:afterDelay:ordispatch_after()but it is a easy to get wrong and is the actual working solution is more complex and harder to understand.If you think that you can just loop a certain number of times and inside call either of these then you are going to see something funny. Both these methods are asynchronous and will not wait for the call to be called. They are merely scheduling it to happen a specified time from "now".
What looping and calling asynchronous methods do
The result of this, as you can imagine, is that nothing will happen for one second. Then all the scheduled calls are going to happen all at once.
This is actually equal to performing the entire loop after one second.
You could make this work if you instead scheduled the next call after each update
For this to happen you would have to schedule the next update in the previous update.
This would do the exact same thing as the repeating timer but has two main disadvantages.
1) It is less intuitive.
In the timer example you would only have to read the timer code to understand that the text would update every second. In this case you would just call
updateText. It is not intuitive by reading that code without looking at the implementation of updateText that this is a repeating process.2) It gets even more complex if you want it to stop.
You can keep a pointer to an
NSTimerand make it stop by simply calling[myTimer invalidate];. The code that uses eitherperformSelector:...ordispatch_after()doesn’t yet support it and if it was built to support that it would be even more complex and less intuitive.