Reputation: 31
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?
Upvotes: 0
Views: 49
Reputation: 31
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
Upvotes: 0