0

只是想用 NSOperationQueue 和 NSInvocationOperation 做一个简单的例子。这是我的代码:

- (void) runMethodsViaOperationQueue {
    NSOperationQueue *thisQueue = [[NSOperationQueue alloc] init];
    NSInvocationOperation *logMethod1Invocation = [[NSInvocationOperation alloc] 
                                                  initWithTarget:self 
                                                  selector:@selector(logMethod1) 
                                                  object:nil];
    [thisQueue addOperation:logMethod1Invocation];
}

logMethod1 只是一个循环的 NSLog 语句,如下所示:

- (void) logMethod1 {
    for (int a = 0; a < 10; a++) {
        NSLog(@"%s --> logMethod1: %i", __FUNCTION__, a);
        if (a == 9) {
            NSLog(@"%s --> ==================", __FUNCTION__);
        }
    }
}

该类在 main 中实例化,其中 runMethodsViaOperationQueue 被调用。

MyOperationTestingClass *instantiateIt = [[MyOperationTestingClass alloc] init];
[instantiateIt runMethodsViaOperationQueue];

事情是,当 runMethodsViaOperationQueue 没有像我期望的那样通过 NSLog 执行任何输出时。谁能帮我澄清为什么这不起作用?

4

1 回答 1

0

我真的试图推断出不止一个 NSInvocationOperation,所以创建一个 NSInvocationOperations 数组:

NSArray *iOps = [NSArray arrayWithObjects:logMethod1Invocation, logMethod2Invocation, nil];

然后将此数组与 addOperations:WaitUntilFinished 一起使用:

[thisQueue addOperations:iOps waitUntilFinished:YES];

执行时,输出将显示多个线程 -

2013-02-15 20:32:29.276 NSOperationTest[1060:1b03] -[MyOperationTestingClass logMethod1] --> logMethod1: 0
2013-02-15 20:32:29.277 NSOperationTest[1060:1a03] -[MyOperationTestingClass logMethod2] --> logMethod2: 0
2013-02-15 20:32:29.280 NSOperationTest[1060:1b03] -[MyOperationTestingClass logMethod1] --> logMethod1: 1
2013-02-15 20:32:29.280 NSOperationTest[1060:1a03] -[MyOperationTestingClass logMethod2] --> logMethod2: 1
于 2013-02-16T04:35:09.823 回答