Introduction of Nsoperation
1. Simple description
Nsoperation for ⽤: Multithreading can also be achieved with nsoperation and Nsoperationqueue
Nsoperation and Nsoperationqueue to implement multithreading specific steps:
(1) Encapsulate the action that needs to be performed in a Nsoperation object first
(2) Then add the Nsoperation object to the Nsoperationqueue
(3) The system will ⾃ move the nsoperationqueue in the nsoperation out
(4) Put the removed Nsoperation encapsulated operation into the ⼀ new thread to hold the ⾏
Sub-class of 2.NSOperation
Nsoperation is an abstract class that does not have the ability to encapsulate operations, and must make ⽤ its subclasses
There are 3 different ways to use the Nsoperation⼦ class:
(1) nsinvocationoperation
(2) Nsblockoperation
(3) Self-defined subclass inherits Nsoperation, realizes internal corresponding ⽅ method
Ii. Specific Description
1.NSInvocationOperation Sub Class
To create an object and perform an action:
Copy Code code as follows:
Create an Action object that encapsulates the task to perform
Nsinvocationoperation Encapsulation operation
Nsinvocationoperation *operation=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (Test) object : nil];
Perform an action
[Operation start];
Note: Once ⾏ is in operation, the target test method is invoked
code example:
Copy Code code as follows:
//
Yyviewcontroller.m
01-nsoperation Basic 1
//
Created by Hole medical self on 14-6-25.
Copyright (c) 2014 itcast. All rights reserved.
//
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Nsoperation: Abstract class, does not have the encapsulation function
Create an Action object that encapsulates the task to perform
Nsinvocationoperation Encapsulation operation
Nsinvocationoperation *operation=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (Test) object : nil];
Perform an action
[Operation start];
}
-(void) test
{
NSLog (@ "--test--%@--", [Nsthread CurrentThread]);
}
@end
Print View:
Note: The action object is executed by default in the main thread, and the new thread is only opened when added to the queue. That is, by default, if the operation is not placed in the queue, it is executed synchronously. Operations are performed asynchronously only if Nsoperation is placed in a nsoperationqueue
2.NSBlockOperation Sub Class
To create an object and add an action:
Copy Code code as follows:
Create a Nsblockoperation Action object
Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{
//......
}];
Add action
[Operation Addexecutionblock:^{
//....
}];
code example:
Code 1:
Copy Code code as follows:
//
Yyviewcontroller.m
02-nstherad Basic 2
//
Created by Hole medical self on 14-6-25.
Copyright (c) 2014 itcast. All rights reserved.
//
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Create a Nsblockoperation Action object
Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{
NSLog (@ "nsblockoperation------%@", [Nsthread CurrentThread]);
}];
Open Perform action
[Operation start];
}
@end
Print View:
Code 2:
Copy Code code as follows:
//
Yyviewcontroller.m
02-nstherad Basic 2
//
Created by Hole medical self on 14-6-25.
Copyright (c) 2014 itcast. All rights reserved.
//
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Create a Nsblockoperation Action object
Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{
NSLog (@ "nsblockoperation------%@", [Nsthread CurrentThread]);
}];
Add action
[Operation Addexecutionblock:^{
NSLog (@ "NSBlockOperation1------%@", [Nsthread CurrentThread]);
}];
[Operation Addexecutionblock:^{
NSLog (@ "NSBlockOperation2------%@", [Nsthread CurrentThread]);
}];
Open Perform action
[Operation start];
}
@end
Note: Operations are performed asynchronously as long as the nsblockoperation encapsulates an operand of > 1
3.NSOperationQueue
Nsoperationqueue ⽤:nsoperation can be adjusted ⽤start⽅ Falay the ⾏ task, but the default is synchronous execution
If you add nsoperation to the Nsoperationqueue (action queue), the actions in Nsoperation are automatically performed asynchronously
Add operations to Nsoperationqueue, automate actions, automatically open threads
Copy Code code as follows:
Create Nsoperationqueue
Nsoperationqueue * Queue=[[nsoperationqueue Alloc]init];
Add an action to the queue
The first way
[Queue Addoperation:operation1];
[Queue Addoperation:operation2];
[Queue Addoperation:operation3];
The second way
[Queue addoperationwithblock:^{
NSLog (@ "nsblockoperation3--4----%@", [Nsthread CurrentThread]);
}];
Copy Code code as follows:
-(void) Addoperation: (Nsoperation *) op;
-(void) Addoperationwithblock: (void (^) (void) block;
code example:
Copy Code code as follows:
//
Yyviewcontroller.m
03-nsoperation Basic 3
//
Created by Hole medical self on 14-6-25.
Copyright (c) 2014 itcast. All rights reserved.
//
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Creating Nsinvocationoperation objects, encapsulating operations
Nsinvocationoperation *operation1=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test1) Object:nil];
Nsinvocationoperation *operation2=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test2) Object:nil];
Create objects, encapsulate operations
Nsblockoperation *operation3=[nsblockoperation blockoperationwithblock:^{
NSLog (@ "nsblockoperation3--1----%@", [Nsthread CurrentThread]);
}];
[Operation3 addexecutionblock:^{
NSLog (@ "nsblockoperation3--2----%@", [Nsthread CurrentThread]);
}];
Create Nsoperationqueue
Nsoperationqueue * Queue=[[nsoperationqueue Alloc]init];
Add an action to the queue
[Queue Addoperation:operation1];
[Queue Addoperation:operation2];
[Queue Addoperation:operation3];
}
Copy Code code as follows:
-(void) test1
{
NSLog (@ "nsinvocationoperation--test1--%@", [Nsthread CurrentThread]);
}
-(void) test2
{
NSLog (@ "nsinvocationoperation--test2--%@", [Nsthread CurrentThread]);
}
@end
Printing effect:
Note: The system automatically takes out the Nsoperation object in the Nsoperationqueue and puts its encapsulated operations into a new thread. In the code example above, there are four tasks, Operation1 and Operation2 each have one task, and Operation3 has two tasks. A total of four tasks, opened four threads. All of the time you perform through tasks is 273, as you can see, these tasks are executed in parallel.
Tip: The queue is out of order, and printing results are not contradictory. This is like, the player A,BC although the starting order is first A, after B, then C, but the order to reach the destination is not necessarily a,b in front, c after.
The following is printed with a for loop, which makes it more obvious to see that the task is executed concurrently.
code example:
Copy Code code as follows:
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Creating Nsinvocationoperation objects, encapsulating operations
Nsinvocationoperation *operation1=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test1) Object:nil];
Nsinvocationoperation *operation2=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test2) Object:nil];
Create objects, encapsulate operations
Nsblockoperation *operation3=[nsblockoperation blockoperationwithblock:^{
for (int i=0; i<5; i++) {
NSLog (@ "nsblockoperation3--1----%@", [Nsthread CurrentThread]);
}
}];
[Operation3 addexecutionblock:^{
for (int i=0; i<5; i++) {
NSLog (@ "nsblockoperation3--2----%@", [Nsthread CurrentThread]);
}
}];
Create Nsoperationqueue
Nsoperationqueue * Queue=[[nsoperationqueue Alloc]init];
Add an action to the queue
[Queue Addoperation:operation1];
[Queue Addoperation:operation2];
[Queue Addoperation:operation3];
}
-(void) test1
{
for (int i=0; i<5; i++) {
NSLog (@ "nsinvocationoperation--test1--%@", [Nsthread CurrentThread]);
}
}
-(void) test2
{
for (int i=0; i<5; i++) {
NSLog (@ "nsinvocationoperation--test2--%@", [Nsthread CurrentThread]);
}
}
@end
Third, concurrent number
(1) Concurrent number: The number of tasks to hold the ⾏ line at the same time. For example, open 3 threads at the same time to perform 3 tasks, the concurrent number is 3
(2) Maximum concurrency: The maximum number of tasks that can be performed at the same time.
(3) The correlation ⽅ method of the ⼤ large concurrent number
Copy Code code as follows:
-(Nsinteger) Maxconcurrentoperationcount;
-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;
Note: If you do not set the maximum number of concurrent, then the number of concurrent is determined by the system memory and CPU, may be more than a little memory, memory less open a little bit.
Note: The value of NUM does not represent the number of threads, only the ID of the thread.
Tip: Maximum concurrent number do not write (less than 5), do not open too much, generally to 2~3, because although the task is handled in the child thread, but the CPU processing these too many child threads may affect the UI, so that the UI card.
Iv. cancellation, suspension and recovery of queues
(1) Cancel all operations of the queue
Copy Code code as follows:
-(void) cancelalloperations;
⽰: You can also invoke the Nsoperation-(void) Cancel⽅ method to cancel a single operation
(2) Pausing and resuming queues
Copy Code code as follows:
-(void) setsuspended: (BOOL) b; Yes represents a paused queue, and no represents a recovery queue
-(BOOL) issuspended; Current state
(3) The application of suspension and restoration: In the TableView interface, a thread download the remote network interface, the UI will have an impact on the user experience to become worse. In this case, you can set up the queue when the user is manipulating the UI (such as scrolling screen), pausing the queue (not canceling the queue), stopping scrolling, and resuming the queues.
V. Operation Priority
(1) Set the priority of Nsoperation in the queue, you can change the operation of the ⾏ priority
Copy Code code as follows:
-(nsoperationqueuepriority) queuepriority;
-(void) Setqueuepriority: (nsoperationqueuepriority) p;
(2) Priority value
Copy Code code as follows:
Nsoperationqueuepriorityverylow = -8l,
Nsoperationqueueprioritylow = -4l,
Nsoperationqueueprioritynormal = 0,
Nsoperationqueuepriorityhigh = 4,
Nsoperationqueuepriorityveryhigh = 8
Description: High priority tasks are more likely to be invoked.
VI. Operational Dependencies
(1) nsoperation can be set between dependencies to ensure the order of execution, ⽐ if the operation a must be done to perform operation B, you can write as follows
Copy Code code as follows:
[Operationb Adddependency:operationa]; Operation B is dependent on the operation
(2) You can create a dependency between nsoperation of different queue
Note: You cannot recycle dependencies (you cannot rely on a b,b and rely on a).
(3) Code example
Copy Code code as follows:
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Creating Nsinvocationoperation objects, encapsulating operations
Nsinvocationoperation *operation1=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test1) Object:nil];
Nsinvocationoperation *operation2=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test2) Object:nil];
Create objects, encapsulate operations
Nsblockoperation *operation3=[nsblockoperation blockoperationwithblock:^{
for (int i=0; i<5; i++) {
NSLog (@ "nsblockoperation3--1----%@", [Nsthread CurrentThread]);
}
}];
[Operation3 addexecutionblock:^{
for (int i=0; i<5; i++) {
NSLog (@ "nsblockoperation3--2----%@", [Nsthread CurrentThread]);
}
}];
Set Operation dependencies
Execute Operation2 First, then execute Operation1, and finally execute Operation3
[Operation3 Adddependency:operation1];
[Operation1 Adddependency:operation2];
Can't be interdependent
[Operation3 Adddependency:operation1];
[Operation1 Adddependency:operation3];
Create Nsoperationqueue
Nsoperationqueue * Queue=[[nsoperationqueue Alloc]init];
Add an action to the queue
[Queue Addoperation:operation1];
[Queue Addoperation:operation2];
[Queue Addoperation:operation3];
}
Copy Code code as follows:
-(void) test1
{
for (int i=0; i<5; i++) {
NSLog (@ "nsinvocationoperation--test1--%@", [Nsthread CurrentThread]);
}
}
-(void) test2
{
for (int i=0; i<5; i++) {
NSLog (@ "nsinvocationoperation--test2--%@", [Nsthread CurrentThread]);
}
}
@end
Print View:
A finish before doing b,b to do c.
Note: Be sure to set up before adding.
Tip: The order in which tasks are added does not determine the order in which they are executed, depending on the order in which they are executed. The purpose of using operation is to get developers to stop caring about threads.
5. Operation of the monitoring
Can listen for execution of an operation completed
Copy Code code as follows:
-(void (^) (void)) Completionblock;
-(void) Setcompletionblock: (void (^) (void) block;
code example
The first way: You can directly follow the task to write what needs to be done, such as here in the download picture, followed by downloading the second picture. But this kind of writing sometimes writes two unrelated operations into a block of code that is not readable.
Copy Code code as follows:
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Create objects, encapsulate operations
Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{
NSLog (@ "-operation-download picture-%@", [Nsthread CurrentThread]);
//..... What to do after downloading a picture
NSLog (@ "--then download the second picture--");
}];
creating queues
Nsoperationqueue *queue=[[nsoperationqueue Alloc]init];
Add a task to the queue (automatic, automatic thread)
[Queue addoperation:operation];
}
@end
The second way:
Copy Code code as follows:
#import "YYViewController.h"
@interface Yyviewcontroller ()
@end
Copy Code code as follows:
@implementation Yyviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Create objects, encapsulate operations
Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{
for (int i=0; i<10; i++) {
NSLog (@ "-operation-download picture-%@", [Nsthread CurrentThread]);
}
}];
Execution of the listening operation completed
operation.completionblock=^{
//..... What to do after downloading a picture
NSLog (@ "--then download the second picture--");
};
creating queues
Nsoperationqueue *queue=[[nsoperationqueue Alloc]init];
Add a task to the queue (automatic, automatic thread)
[Queue addoperation:operation];
}
@end
Print View:
Note: After the last task finishes executing, the operation.completionblock=^{} code snippet is executed and executes at the current thread (2).