We can use Nsoperation and nsoperationqueue for multithreaded development, and the concept of nsoperationqueue is similar to a thread pool, which provides object-oriented syntax compared to nsthread,nsoperation.
The process of using nsoperation is to create a operation
Nsoperation is not usually used directly, we use its subclasses nsinvocationoperation or nsblockoperation, or custom nsoperation subclasses, which are described in the following three ways.
Nsinvocationoperation
- (void) viewdidload{[Super Viewdidload]; //Do any additional setup after loading the view.nsinvocationoperation*operation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (threadoperation)Object: nil]; //if the direct use of Start,operation will run immediately in the main thread, we basically do not use this//[Operation start];Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; //when operation is added to Operationqueue, Operationqueue automatically executes the Start method and runs in multiple threads[queue addoperation:operation];}
About Nsoperationqueue We can also set its related properties
Queue.maxconcurrentoperationcount Gets or sets the maximum number of concurrent runs, the default value is-1, which means that the number of concurrently running threads is not limited
Queue. Name set thread pool names
[Nsoperationqueue currentqueue] Get the current thread pool
[nsoperationqueue mainqueue] get the main thread pool
[Queue cancelalloperations] executes the Cancel method on the thread pool's threads to set the cancellation token,
Nsblockoperation
Nsblockopration the use of the process is basically consistent with nsinvocationoperation, just use block instead of selector
- (void) viewdidload{[Super Viewdidload]; //Do any additional setup after loading the view._imageview= [[Uiimageview alloc] Initwithframe:cgrectmake ( +, +, -, the)]; [Self.view Addsubview:_imageview]; Nsblockoperation*operation = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%HHD", [Nsthread ismainthread]); NSData*data = [NSData datawithcontentsofurl:[nsurl urlwithstring:@"http://www.iyi8.com/uploadfile/2014/1002/20141002112243630.jpg"]]; [[Nsoperationqueue Mainqueue] Addoperationwithblock:^{NSLog (@"%HHD", [Nsthread ismainthread]); [_imageview setimage:[uiimage Imagewithdata:data]; }]; }]; //Add the completed block for OperationOperation.completionblock = ^{NSLog (@"Operation Done"); }; Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Queue addoperation:operation];}
The above code in multi-threaded network request picture, and in the main thread to update the UI, nsblockoperation than nsinvocationoperation more convenient to use
Custom Nsoperation Subclasses
We have directly used the Nsoperation subclass provided in the framework, and we can define the Nsoperation subclass ourselves.
The steps to customize operation are as follows
1 Inheritance Nsoperation
2 Implementing the main function
3 Creating an auto-free pool in the main function
4 Write the task code in the auto-release pool
Here we customize a nsoperation subclass to download images
ZLTOperation.h#import<Foundation/Foundation.h>@protocoldownimageprotocal;@interfacezltoperation:nsoperation-(ID) Initwithimageurl: (nsurl *) URL Delagete: (ID<DownImageProtocal>)Delegate;@end@protocolDownimageprotocal <nsobject>-(void) Updateviewwithimage: (UIImage *) image;@endzltoperation.m#import "ZLTOperation.h"@interfacezltoperation () {Nsurl*_imageurl; ID<DownImageProtocal>_delegate;}@end@implementationzltoperation-(ID) Initwithimageurl: (nsurl *) URL Delagete: (ID<DownImageProtocal>)Delegate{ Self=[Super Init]; if(self) {_imageurl=URL; _delegate=Delegate; } returnSelf ;}- (void) Main {@autoreleasepool {//whether the task was canceled if([self iscancelled]) {return; } NSData*data =[NSData Datawithcontentsofurl:_imageurl]; //whether the task was canceled if([self iscancelled]) {return; } if([_delegate respondstoselector: @selector (updateviewwithimage:)]) {[(NSObject*) _delegate performselectoronmainthread: @selector (updateviewwithimage:) withobject:[uiimage Imagewithdata:data ] Waituntildone:no]; } }}@end
Test
ZViewController.h@interfaceZviewcontroller:uiviewcontroller<downimageprotocal>@endZVIEWCONTROLLER.M@interfaceZviewcontroller () {Uiimageview*_imageview;}@end@implementationZviewcontroller- (ID) Initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *) nibbundleornil{ Self=[Super Initwithnibname:nibnameornil Bundle:nibbundleornil]; if(self) {//Custom Initialization } returnSelf ;}- (void) viewdidload{[Super Viewdidload]; //Do any additional setup after loading the view._imageview= [[Uiimageview alloc] Initwithframe:cgrectmake ( +, +, -, the)]; [Self.view Addsubview:_imageview]; Zltoperation*operation = [[Zltoperation alloc] Initwithimageurl:[nsurl urlwithstring:@"http://www.iyi8.com/uploadfile/2014/1002/20141002112243630.jpg"] delagete:self]; //Add the completed block for OperationOperation.completionblock = ^{NSLog (@"Operation Done"); }; Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Queue addoperation:operation];}- (void) Updateviewwithimage: (UIImage *) Image {_imageview.image=image;}@end
Nsoperation other common methods and properties
-(BOOL) iscancelled;
-(void) cancel; Cancel a task
-(void) Setcompletionblock: (void (^) (Void)) block Add task complete block
-(double) threadpriority
-(void) SetThreadPriority: (Double) p task priority
-(void) adddependency: (nsoperation *) op;
-(void) removedependency: (nsoperation *) op;
-(Nsarray *) dependencies; Add Dependency
Dependencies are used to control the order of thread execution, and if a adds B as his dependency, then action A is performed only when Operation B is complete, and the operation dependency can be set more than one, for example a depends on B, B depends on C ... However, do not set a circular dependency (for example, a relies on b,b dependent on C,c and a), otherwise it will not be executed.
Concurrency of Nsoperation
When we mentioned the start method of directly executing operation, operation would run on the main thread, because nsoperation default is non-concurrency, we can implement the concurrency operation class ourselves, which requires overloading a series of methods, The general steps for creating concurrent operation are as follows
- You need to create a
subclass
- In addition to overloading
main methods, implementing concurrency you also need at least overloading,, start isConcurrent isExecuting , isFinished four methods
- In
start , create Thread or invoke an asynchronous function
- Update
isExecuting , and send the corresponding KVO message
- After the task is over, you have to update
isExecuting and isFinished send the corresponding KVO message
In general we do not need to create concurrent nsoperation, with Nsoperationqueue to invoke, instead of calling start yourself
iOS multi-thread nsoperation