IPhone DevelopmentAbout NSInvocationOperationMultithreadingThe tutorial is the content to be introduced in this article, mainly to introduceThreadFor more information, see.MultithreadingProgramming is to prevent the masterThreadBlocking, increase operation efficiency, and so on. While the originalMultithreadingThere are many problems with the method, includingThreadLocked.
In Cocoa, Apple provides the NSOperation class and an excellent multi-threaded programming method. This section describes the subset of NSOperation and NSInvocationOperation of the simple method:
- @ Implementation MyCustomClass
- -(Void) launchTaskWithData :( id) data {
- // Create an NSInvocationOperation object and initialize it to the Method
- // Here, the value after the selector parameter is the Method function you want to run in another thread. Method)
- // Here, the object value is the data to be passed to the previous method.
- NSInvocationOperation * theOp = [[NSInvocationOperation alloc]
- InitWithTarget: selfselector: @ selector (myTaskMethod :) object: data];
- // Add the Operation "Operation" we created to the shared queue of the local program and the method will be executed immediately)
- // In more cases, we create an "operation" queue by ourselves.
- [[MyAppDelegate implements doperationqueue] addOperation: theOp];
- }
- // This is the "method" that actually runs in another thread"
- -(Void) myTaskMethod :( id) data {
- // Perform the task.
- }
- End
An NSOperationQueue operation queue is equivalent to a thread manager rather than a thread. Because you can set the number of threads that can run in parallel in this thread manager. The following describes how to create and initialize an operation queue:
- @ Interface MyViewController: UIViewController {
- NSOperationQueue * operationQueue;
- // Declare the queue in the header file
- }
- @ End
- @ Implementation MyViewController
- -(Id) init {self = [super init];
- If (self) {operationQueue = [[NSOperationQueue alloc] init];
- // Initialize the operation queue
- [OperationQueue setMaxConcurrentOperationCount: 1];
- // This limits the queue to run only one thread at a time
- // This queue is ready for use.
- }
- Return self;
- }
- -(Void) dealloc {
- [OperationQueue release];
- // As Alan often said, we are a good citizen of the program and need to release the memory!
- [Super dealloc];
- }
- @ End
After a brief introduction, we can find that this method is very simple. Many times we useMultithreadingOnly to prevent the masterThreadAnd NSInvocationOperation is the simplestMultithreadingProgramming is often used in iPhone programming.
Summary:IPhone DevelopmentAbout NSInvocationOperationMultithreadingThe content of this tutorial has been introduced. I hope this article will help you!