为什么这些NSInvocationOperation实际上不会运行?

时间:2013-02-16 01:54:43

标签: nsoperationqueue nsinvocationoperation

尝试使用NSOperationQueue& amp; 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。任何人都可以帮我澄清为什么这不起作用?

1 个答案:

答案 0 :(得分: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