Reasons for multithreading in iOS:
1. In iOS, only the main thread has the right to directly modify the Ui.
2. The main thread stack of the iPhone is 1 M, and the newly opened thread stack is 512 K.
3. Multi-task, multi-core, efficiency, and user experience are jointly determined.
(1) GCD (Grand Central dispatch) block and dispatch, which can simplify multi-core multi-thread programming and will be supported by iOS4 later
1. The block definition is similar to the function pointer; the block object (block object );
A block array may exist;
However, block is stored in the function stack. Pay attention to the lifecycle in braces;
2. Typical block usage: The block application in the image downloading Application and the use of nested asynchronous block blocks. If the previous step is OK, update the block through the UI.
Dispatch_async (dispatch_queue_create ("com. enormego. EGOImageLoader", NULL), ^ {
UIImage * image = styler (anImage );
[[EGOCache currentCache] setImage: image forKey: keyForURL (aURL, style) withTimeoutInterval: 604800];
Dispatch_async (dispatch_get_main_queue (), ^ {
Completion (image, aURL, nil );
});
});
(2) NSOperation and NSOpertionQueue
1. An operation class inherited from NSOperation. The implementation of this class must have the (void) main () method
2. Put the NSOperation instance into the NSOpertionQueue.
3. You can set the operands that can be performed simultaneously in NSOpertionQueue.
(3) NSThread
1. detachNewThreadSelector this is a simple method, and no thread cleaning is required.
[NSThread detachNewThreadSelector: @ selector (myThreadMainMethod :) toTarget: self withObject: nil];
2, NSThread initialWithTarget, (void) start; method, you can create a thread, but choose the appropriate time to start the thread
NSThread * myThread = [[NSThread alloc] initWithTarget: self
Selector: @ selector (myThreadMainMethod :)
Object: nil];
[MyThread start];
(4) synchronization between threads
1. Atomic lock attributes, automic, noautomic, and variables can ensure multi-thread access
2, NSCondition, can provide a synchronization lock with conditions. When unlocking, you must enter the same conditions to unlock
3. NSLock, lock, and unlock are relatively simple synchronization locks.
4, @ synchronized (anObject) is a simpler method. It is usually used to create a single-instance object.