Brief introduction:
1. Nsoperation is an object-oriented package of Apple for GCD, which is OC
2, Nsoperation also provides some gcd is not particularly easy to implement the function
3. Add the operation to the queue and the operation will be executed "asynchronously" immediately.
4, Nsoperation is an abstract class, does not have the ability to encapsulate operations, it must use its subclasses
1>nsinvocationoperation
2>nsblockoperation
3> custom class Inheritance nsoperation, implementing an internal method
Code implementation:
Example 1:nsinvocationoperation
@interface Tbviewcontroller ()
@property (Nonatomic,strong) nsoperation *myqueue;
@end
Lazy Loading
-(Nsoperationqueue *) myqueue
{
if (_myqueue = = nil) {
_myqueue =[[Nsoperationqueue alloc]init];
}
return _myqueue;
}
-(void) Touchesbegan: (Nsser *) touches withevent: (Uievent *) event
{
[Self opDemo1];
}
-(void) OpDemo1
{
Operation
Nsinvocationoperation *op =[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (downloadimage) Object:nil];
Lets the operation start, and if the Start method is used, the operation is performed on the current thread
[op start];
Adds an action to the queue, and the operation is immediately "asynchronously" executed
[Self.myqueue Addoperation:op];
}
Download image
-(void) downloadimage
{
NSLog (@ "Download Image:%@", [Nsthread CurrentThread]);
}
Example 2:nsblockoperation
Nsoperationqueue instantiated objects are concurrent queues
-(void) Touchesbegan: (Nsser *) touches withevent: (Uievent *) event
{
[Self opDemo1];
}
-(void) OpDemo2
{
Operation
for (int i = 0;i <; i + +)
{
Nsblockoperation *op = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "Block ===%@", [Nsthread CurrentThread]);
}];
Add to queue by running you can see that it is a "concurrent" queue
[Self.myqueue Addoperation:op];
}
}
Example 3: Add block directly
-(void) Touchesbegan: (Nsser *) touches withevent: (Uievent *) event
{
[Self OPDEMO3];
}
-(void) OpDemo3
{
for (int i = 0; i <; i++)
{
[Self. Myqueue addoperationwithblock:^{
NSLog (@ "=====%@", [Nsthread CurrentThread]);
}];
}
}
Example 4: Inter-thread communication
-(void) Touchesbegan: (Nsser *) touches withevent: (Uievent *) event
{
[Self OpDemo4];
}
-(void) OpDemo4
{
[Self.myqueue addoperationwithblock:^{
NSLog (@ "Download Image:%@", [Nsthread CurrentThread]);
Download complete need to update ui,mainqueue home row
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{
NSLog (@ "Main%@", [Nsthread CurrentThread]);
}];
}];
}
iOS Development-nsoperation Introduction