IOS multithreading technology 2
IOS multithreading technology 2 NSOperation
NSInvocationOperation
// Create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // create a subtask, define a subtask to be a subclass of NSOperation NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (dosomething :) object: @ NSInvocationOperation]; // after a task is added to the queue, the thread [queue addOperation: op] is automatically enabled.
NSBlockOperation
// Create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // create the NSBlockOperation object NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {[self doSomething];}]; // join the queue [queue addOperat: operation];
Demo:
Next I will use two NSOperation methods to create an example to implement the same functions as in the previous article,
# Import ViewController. h --- @ interface ViewController () @ property (weak, nonatomic) IBOutlet UIImageView * iamgeView; @ property (weak, nonatomic) IBOutlet UILabel * lable; @ property (nonatomic, strong) NSOperationQueue * queue; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // 1. NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (dosomething :) object: @ NSInvocationOperation]; op. name = @ xiaoming; NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [queue addOperation: op]; NSLog (@ % @, queue. operations); _ queue = queue;}-(void) dosomething :( NSString *) str {// time-consuming operation [NSThread sleepForTimeInterval: 3]; // you need to update the UI [self supplied mselecw.mainthread: @ selector (updateLable :) withObject: str waitUntilDone: YES];}-(void) updateLable :( NSString *) in the main thread *) str {if ([[NSThread currentThread] isMainThread]) {NSLog (@ main thread >>>% s ,__ func _);} _ lable. text = str;}-(IBAction) btnAction :( UIButton *) sender {NSBlockOperation * blockOp = [NSBlockOperation blockOperationWithBlock: ^ {// time-consuming operation [NSThread sleepForTimeInterval: 3]; // create url NSString * urlStr = @ brief NSURL * url = [NSURL URLWithString: urlStr]; NSData * data = [NSData dataWithContentsOfURL: url]; UIImage * image = [UIImage imageWithData: data]; // update UI [self defined mselecw.mainthread: @ selector (updateImageView :) withObject: image waitUntilDone: YES];}]; [_ queue addOperation: blockOp];}-(void) updateImageView :( UIImage *) img {if ([[NSThread currentThread] isMainThread]) {NSLog (@ main thread >>>>>>>% s ,__ FUNCTION __);} _ iamgeView. image = img;} @ end
Running result:
15:03:33. 909 05-NSOperationDemo [3284: 874300] (
"{Name = 'xiaoming '}"
)
15:03:36. 911 05-NSOperationDemo [3284: 874300] main thread >>>-[ViewController updateLable:]
15:03:47. 730 05-NSOperationDemo [3284: 874300] main thread >>>>>-[ViewController updateImageView:]