简体   繁体   中英

why won't these NSInvocationOperation's actually run?

Just trying to do a simple example with NSOperationQueue & NSInvocationOperation. Here's my code:

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

logMethod1 is just a looped NSLog statement, as in:

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

The class is instantiated in the main, where runMethodsViaOperationQueue is called.

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

Thing is, when runMethodsViaOperationQueue executes nothing outputs as I'd expect via NSLog. Can anyone help me clarify why this isn't working?

I was really trying to extrapolate to more than one NSInvocationOperation, so create an array of the NSInvocationOperations:

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

Then use this array with addOperations:WaitUntilFinished:

[thisQueue addOperations:iOps waitUntilFinished:YES];

When executed, the output will show more than one thread -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM