NSOperation blocks UI painting?

后端 未结 2 409
长发绾君心
长发绾君心 2021-02-04 09:39

I\'m after some advice on the use of NSOperation and drawing:

I have a main thread create my NSOperation subclass, which then adds it to an

2条回答
  •  一生所求
    2021-02-04 10:18

    The method in the observer that is performed in response to your notification is not being performed on the main thread.

    So, in that method, you can force another method to run on the main thread using performSelectorOnMainThread:withObject:waitUntilDone:.

    For example:

    MyOperation.m

    - (void)main {
        for (int i = 1; i <= 5; i++) {
            sleep(1);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"GTCNotification" object:[NSNumber numberWithInteger:i]];
        }
    }
    

    MyViewController.m

    - (void)setupOperation {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationResponse:) name:@"GTCNotification" object:nil];
    
        NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
        MyOperation *myOp = [[MyOperation alloc] init];
    
        [opQueue addOperation:myOp];
    
        [myOp release];
        [opQueue release];
    }
    
    - (void)myNotificationResponse:(NSNotification*)note {
        NSNumber *count = [note object];
        [self performSelectorOnMainThread:@selector(updateView:) withObject:count waitUntilDone:YES];
    }
    
    - (void)updateView:(NSNumber*)count {
        countLabel.text = count.stringValue;
    }
    

提交回复
热议问题