Update UITextView during recursive function is running

↘锁芯ラ 提交于 2019-12-25 03:26:26

问题


I have a view controller with a UITextView loaded into the frame. I want to update the text of the UITextView every time the function calls itself.

I attempt to update the UITextView on the main thread but it doesn't seem to set the text of the View UNTIL after the recursive function is done running.

'Maze.h' is the object that defines the protocol and 'MainViewController.m' is the delegate.

Heres the code for the controller:

'MainViewController.m'

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    Maze *aMaze = [[Maze alloc] initWithMaze:@"Maze.txt" andUpdate:true everyXSeconds:1];
    [aMaze setDelegate:self];
    if (![aMaze parseFile]) {
        exit(2);
    }

    if ([aMaze solve:-1 y:-1 z:-1]){
        NSLog(@"%@", [aMaze printMazeHorizontally]);
        NSLog(@"Escapable: %@", [aMaze getMoveSequence]);
    } else {
        NSLog(@"Unescapable");
        exit(1);
    }
}

- (void)didMakeMove:(NSString *)maze {
    NSLog(@"%@", maze);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.maze setText:maze];
    });
}

'Maze.m'

- (BOOL)solve:(NSInteger)x y:(NSInteger)y z:(NSInteger)z
{
...

...
        [self.delegate didMakeMove:self.printMazeVertically];
...
...
}

The UITextView just doesn't seem to update until -(BOOL)solve::: is done running. Which only updates once instead of multiple times.

Not sure why this is happening.

Any ideas on how to update the UITextView?

I thought that updating the UI should be done on the main thread?

Solution:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([aMaze solve:-1 y:-1 z:-1]){
            NSLog(@"%@", [aMaze printMazeHorizontally]);
            NSLog(@"Escapable: %@", [aMaze getMoveSequence]);
        } else {
            NSLog(@"Unescapable");
            exit(1);
        }
    });

回答1:


Drawing is performed later in the runloop run, or on the next runloop run. Thus, if you block the main thread while your recursion is running, UI will not update until after you end your recursion.

Consider changing your design. Move the taxing recursion to a background thread, and update the UI using GCD.



来源:https://stackoverflow.com/questions/25980399/update-uitextview-during-recursive-function-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!