iOS has three multithreaded technologies:
- 1.NSThread
- Created in two ways:
- 1. Instance method:
- -(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument
- You can set thread information such as thread priority before you run a thread operation by creating a thread object before you run the thread action
- 2. Class method:
- + (void) Detachnewthreadselector: (SEL) Aselector Totarget: (ID) atarget withobject: (ID) anargument
- create thread directly and start running thread
- usage Example:
- [Nsthread detachnewth Readselector: @selector (dosomething:) totarget:self Withobject:nil];
- nsthread* myThread = [[Nsthread alloc] initwithtarget:self selector: @selector (dosomething:) Object:nil];
- [MyThread start];
- parameter explanation:
- Selector: The method that the thread executes, the selector can have only one parameter, and cannot have a return value.
- target:selector The object sent by the message
- argument: The only parameter that is transmitted to target, or nil
- does not show the method of creating the thread:
- Call NSObject class method Performselectorinbackground:withobject: The
- demonstration is performed by default in a child thread:
- [OBJ Performselectorinbackgro und: @selector (dosomething) Withobject:nil];
- Demonstration Example: (Sub-thread asynchronous download, main thread UI update)
#import "ViewController.h"#defineKurl @ "http://avatar.csdn.net/2/c/d/1_totogo2010.jpg "@interfaceViewcontroller ()@end@implementationViewcontroller- (void) Viewdidload{[super Viewdidload];//[Nsthread detachnewthreadselector: @selector (downloadimage:) totarget:self Withobject:kurl];Nsthread *thread = [[Nsthread alloc]initwithtarget:self selector: @selector (downloadimage:)Object: Kurl]; [Thread start];}-(void) Downloadimage: (NSString *) Url{nsdata*data =[[NSData alloc] Initwithcontentsofurl:[nsurl Urlwithstring:url]]; UIImage*image =[[UIImage alloc]initwithdata:data];if(Image = =Nil) {}Else{[Self performselectoronmainthread: @selector (updateUI:) withobject:image Waituntildone:yes];//execute (inter-thread communication) in the main thread}}-(void) UpdateUI: (uiimage*) Image{self.imageview.image=image;}@end
- 2.NSOperation
- To encapsulate the independent unit of work in the execution program, providing an asynchronous execution mechanism.
- Nsoperation class as abstract class, based on template method design pattern
- The operations can be run independently or in conjunction with the Operation queue.
- There are two ways of using it:
- 1. Use a defined two subclass: Nsinvocationoperation and Nsblockoperation.
- Nsinvocationoperation:
- How to create:
- nsinvocationoperation* operation = [[Nsinvocationoperation alloc]initwithtarget:self selector: @selector ( Customtaskmethod:) Object:params];
- Nsblockoperation:
- How to create:
- nsblockoperation* blockoperation = [nsblockoperation blockoperationwithblock: ^{
- To do the task.
- }];
- After creating the blockoperation, you can call Addexecutionblock: method to add more block
- Demonstration examples:
#import "ViewController.h"#defineKurl @ "http://avatar.csdn.net/2/c/d/1_totogo2010.jpg "@interfaceViewcontroller ()@end@implementationViewcontroller- (void) Viewdidload{[super Viewdidload]; Nsinvocationoperation*operation =[[Nsinvocationoperation alloc]initwithtarget:selfselector: @selector (downloadimage:)Object: Kurl]; Nsoperationqueue*queue =[[Nsoperationqueue alloc]init]; [Queue addoperation:operation];//additional setup after loading the view, typically from a nib.}-(void) Downloadimage: (NSString *) Url{nslog (@"url:%@", URL); Nsurl*nsurl =[Nsurl Urlwithstring:url]; NSData*data =[[NSData Alloc]initwithcontentsofurl:nsurl]; UIImage* Image =[[UIImage Alloc]initwithdata:data]; [Self Performselectoronmainthread: @selector (updateUI:) withobject:image waituntildone:yes];}-(void) UpdateUI: (uiimage*) Image{self.imageview.image=image;}
-
-
- 2. Inheriting nsoperation
- 1. Provide a custom initialization method that provides the initialization process before executing operation, prepares the Operation state
- 2. Just inherit one method of overriding Nsoperation main
- 3. Then put the object of the Nsoperation subclass into the Nsoperationqueue queue and the queue will start and start processing it
- Demonstration examples:
@interfacemovefileoperation:nsoperation- (ID) Initwithsrcurl: (Nsurl *) Srcurl Todestinationurl: (nsurl*) Desurl;@end//movefileoperation.m@interfacemovefileoperation () @property (retain) Nsurl*Srcurl, @property (retain) Nsurl*Desurl;@end@implementationmovefileoperation@synthesizeRooturl, queue;- (ID) Initwithsrcurl: (Nsurl *) Srcurl Todestinationurl: (nsurl*) Desurl; { Self=[Super init];if(self) {Self.srcurl=Srcurl;self.desurl=Desurl;}returnSelf ;}- (void) main{if([self iscancelled]) {return;} Nsdirectoryenumerator*itr =[[Nsfilemanager Defaultmanager] EnumeratorAtURL:self.srcURL includingpropertiesforkeys:niloptions: ( Nsdirectoryenumerationskipshiddenfiles|nsdirectoryenumerationskipspackagedescendants) Errorhandler:nil]; Nserror*error = [NserrorNew]; for(Nsurl *urlinchITR) {if([self iscancelled]) {// Break; }Else{nsstring*filename =[url lastpathcomponent]; Nsurl*desfileurl =[Self.desurl Urlbyappendingpathcomponent:filename]; [[Nsfilemanager Defaultmanager] copyitematurl:url tourl:desfileurl error:&ERROR];} }}
-
-
-
- The operation support thread cancellation behavior through the IsCancelled method:
- The common locations for correctly calling iscancelled include:
- 1. Before the actual implementation of the work
- 2. In each loop of the actuator, if a single execution takes a long time to add the number of calls as appropriate
- 3. Code where the program is relatively easy to terminate.
- To configure Operation dependencies:
- Call the Adddependency: method to establish a dependency relationship between the two Operation objects:
- This one-way relationship indicates that the current operation object cannot be executed until the target operation object finishes executing.
- The dependency of the Operation object is not limited to the same operation queue.
- Operation objects that have dependencies can be added to different operations queues.
- However, you cannot add circular dependencies between operation.
- Add Completion Block:
- The Setcompletionblock: method allows you to complete the work of adding completion block, where you can distribute operation completed messages.
- How to execute Operation:
- 1. Add the Operation object to the Operations queue Nsoperatinqueue object:
- nsoperationqueue* aqueue = [[NSO Perationqueue alloc] init];
- 1.//Add A single operation
- [Aqueue Addoperation:anop];
- 2.//ADD Multiple operations
- [Aqueue addoperations:anarrayofops waituntilfinished:no];
- 3.//ADD a block
- [Aqueue addoperationwithblock:^{
- /* do something. */
- }];
The
- Nsoperationqueue is designed to be used concurrently to execute the Operation,setmaxconcurrentoperationcount: method to set the maximum number of operations queue execution in parallel. The
- needs to set dependencies between operation to ensure that the order in which they are executed is what you want.
- 2. Manual execution of operation:
- A operation is considered to be operational only if its IsReady method returns YES. The
- IsReady method is integrated into the Nsoperation dependency management system to ensure operation dependency status.
- operation only starts running when the dependencies are clear. When
- executes operation manually, its Start method must be called.
- Cancel Operation:
- Once the operation queue is joined, the operation queue has the operation and it cannot be deleted.
- The only way to bring up operation is to cancel it (cancel)
- A operation on a cancel can cancel its execution, and calling Cancelalloperations on the action queue object cancels all operation.
- Operation's cancellation behavior is also considered complete (finished), and other operation objects that depend on it receive a KVO notification to clear the dependency.
- Wait for operation to end:
- If the process that creates the operation needs to handle the operation results, you can use the Nsoperation Waituntilfinished method to block code until operation is complete (never wait for a operation to end on the main thread)
- To suspend and reply to a queue:
- Call the setsuspended: Method of the Nsoperationqueue object to manipulate the queue to suspend. Suspending a queue does not hinder the operation that is currently executing, it simply blocks the execution of the new operation.
- 3.GCD
Objective-c Multithreading