Go free http://blog.csdn.net/totogo2010/There are two ways to use Nsoperation, one is to use a defined two sub-class:
Nsinvocationoperation and Nsblockoperation.
The other is to inherit Nsoperation
If you are familiar with java,nsoperation, it is similar to the Java.lang.Runnable interface. Like Java's runnable, Nsoperation is also designed to be extended by simply inheriting one of the methods of overriding Nsoperation main. Equivalent to the Runnalbe run method in Java. Then put the object of the Nsoperation subclass into the Nsoperationqueue queue, and the queue will start and process it.
nsinvocationoperation Example:
As in the previous blog post, we implemented an example of downloading a picture. Create a new single View app and drag and drop a ImageView control to the Xib interface.
The implementation code is as follows:
#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:self Selector: @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;}
- You can see in the Viewdidload method that we built a background thread with nsinvocationoperation and put it in Nsoperationqueue. The background thread executes the Downloadimage method.
- The Downloadimage method handles the logic of downloading pictures. After the download is complete, use Performselectoronmainthread to execute the main thread UpdateUI method.
- UpdateUI and displays the downloaded picture in the picture control.
Run can see the download picture displayed on the interface.
The second way of inheriting nsoperation
Implement the Main method in the. m file, and the main method writes the code to execute.
How do I control the number of threads in a thread pool?
Many nsoperation can be added to the queue, and nsoperationqueue can be thought of as a thread pool that adds operations (nsoperation) to the queue. Threads in a thread pool can be considered consumers, taken from a queue, and executed.
Set by the following code:
[Queue Setmaxconcurrentoperationcount:5];
The number of threads in the thread pool, which is the number of concurrent operations. By default, -1,-1 represents no limit, which runs all the operations in the queue at the same time.