1
votes

I want to subclass NSOperation to make it concurrent, according to the Apple doc, I must override the following methods to implement a concurrent operation:

  1. start
  2. isExecuting
  3. isFinished
  4. isAsynchronous

But as per my test result, I can let the NSOperation object run in a second thread without implementing the "isExecuting","isFinished" and "isAsynchronous" methods.I just write the code.

[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];

in the start method and then in the main thread I execute

[myOperation start]

then the operation can execute in a second a second thread instead of main thread. Can someone explain this phe

2
Use NSOperationQueue to run your NSOperation. Setup the queue to be concurrent (or serial).rmaddy
NSOperationQueue always executes operations concurrently, while taking dependencies into account.It cannot be serial modeCoinnigh
@Coinmigh it can be serial if you set the max concurrent to 1.rmaddy
@rmaddy, yes, you are right. I understand the question I asked by reading the apple doc again, thanks.Coinnigh

2 Answers

0
votes

You are using a solution that today would be considered awful.

Either you need the advantages that NSOperation has to offer - you've just thrown all of that out of the window. Good luck. Or you don't need the advantages of NSOperation, then please learn about GCD and blocks and dispatch_async to make your life ten times easier.

0
votes

Agree with @gnasher729. If you just want to launch an asynchronous method, don't bother to use NSOperation. GCD and blocks will be a lot more easier.

Back to why you have to implement isExecuting, isFinished, isAsynchronous besides start, it's because NSOperation does extra work about state, priority, and dependency management.

For example, you might want to cancel an asynchronous operation when you leave a view. The default implementation of cancel method in NSOperation depends on the state of operation. If the operation is not in a queue it will be finished immediately; If it's in a queue but has not been started yet, its isCancelled and isReady will be set to YES, and wait for the queue to call its start method. The start method will check the value of isCancelled property; if YES, it'll be finished immediately.