There are three methods to implement multithreading in iOS development: NSThread, NSOperation, and GCD. This article describes the specific implementation of the three methods.
1. NSThread
There are two ways to initialize a thread:
/******* NSObject class method ****************/[self defined mselectorinbackground: @ selector (secondMethod) withObject: self];/******** NSThread. There are two methods: *********** // 1. the class method automatically runs the main method [NSThread detachNewThreadSelector: @ selector (firstMethod) toTarget: self withObject: nil]; // 2. the alloc thread needs to start NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (firstMethod) object: nil]; [thread start];
2. NSOperation
NSOperationQueue * queue = [[NSOperationQueue alloc] init]; queue. maxConcurrentOperationCount = 3; // maximum number of concurrent threads for (int I = 0; I <10; I ++) {MyOperation * opr = [[MyOperation alloc] init]; // customize an operation class that inherits from NSOperation opr. time = I; [queue addOperation: opr]; [opr release];}MyOperation. h
#import
@interface MyOperation : NSOperation@property (nonatomic, assign) int time;@end
MyOperation. m
# Import "MyOperation. h "@ implementation MyOperation @ synthesize time; // The main method-(void) main {sleep (self. time); NSLog (@ "% d", self. time) ;}@ end
3. GCD
I will introduce GCD in another article. Here I will write the usage directly.
// Create a serial thread queue. The first parameter is the queue name, and the second parameter is unknown: dispatch_queue_t opqueue = dispatch_queue_create ("my operation queue", NULL ); // asynchronous execution thread, execute the block statement dispatch_async (opqueue, ^ {[self first] ;}) in t; // get a parallel thread queue, the first parameter is the priority dispatch_queue_t opqueue2 = dispatch_get_global_queue (0, 0); dispatch_async (opqueue2, ^ {[self second];});
In addition, these threads cannot operate the UI, but can call back to execute UI operations in two ways:
// Return to the main thread // The first method // [self initiate mselecw.mainthread: @ selector (first) withObject: self waitUntilDone: NO]; // The second method is dispatch_async (dispatch_get_main_queue (), ^ {_ imageView. image = img ;});