Multithreading in IOS development and multithreading in ios development
I. Five ways to create Multithreading |
1. method 1 for enabling threads
NSThread * thread=[[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];
2. method 2
[NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];
3. Method 3 for enabling a thread
[self performSelectorInBackground:@selector(_update) withObject:nil];
4. Method 4 of enabling a thread
NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock: ^ {for (int I = 0; I <50; I ++) {printf ("subthread \ n") ;}}];
5. Method 5 for enabling threads
// Step 1 enable the thread pool NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // set the number of concurrent threads [queue setMaxConcurrentOperationCount: 2]; // create multiple threads and add them to the thread pool NSInvocationOperation * thread1 = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (_ update1) object: nil]; NSInvocationOperation * thread2 = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (_ update2) object: nil]; [thread1 setQueuePriority: Unknown]; [thread2 unknown: Unknown]; [queue addOperation: thread1]; [queue addOperation: thread2];
2. multi-threaded application instances and image loading. |
1. Core Ideas
Considering that loading a network image will delay, loading in a main thread will affect the rendering of the control. At this time, you can adopt multiple threads. After asynchronous loading, refresh the UI.
2. Implementation ideas
Multi-thread download is implemented by adding a category for UIImageView.
Main Code:
#import "UIImageView+thread.h"@implementation UIImageView(load)- (void) setImageWithUrl:(NSString *)url{ [self performSelectorInBackground:@selector(_loadImage:) withObject:url];}- (void) _loadImage:(NSString *)u{ @autoreleasepool { NSURL *url=[NSURL URLWithString:u]; NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO]; }}