IPhone DevelopmentApplication in progressNSOperation MultithreadingUse is the content to be introduced in this article. First, create a Thread class, RequestOperation, which inheritsNSOperationThen, in the Controller class, create an NSOperationQueue object and add the line to the sequence. It will automatically get the thread we added from NSOperationQueue, and then run the starting method.
- # Import "RootViewController. h"
- @ Implementation RootViewController
- # Pragma mark-
- # Pragma mark View lifecycle
- -(Void) buttonClicked :( id) sender {
- _ Queue = [[NSOperationQueue alloc] init];
- // The first request
- NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http: www.google.com"];
- RequestOperation * operation = [[RequestOperation alloc] initWithRequest: request];
- [_ Queue addOperation: operation];
- [Operation release];
- // Second request
- // NSURLRequest * request2 = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http: www.baidu.com"];
- // RequestOperation * operation1 = [[RequestOperation alloc] initWithRequest: request2];
- // Operation1.message = @ "operation1 ---";
- // [_ Queue addOperation: operation1];
- }
- # Import <Foundation/Foundation. h>
- @ Interface RequestOperation: NSOperation {
- NSURLRequest * _ request;
- NSMutableData * _ data;
- NSString * message;
- }
- @ Property (nonatomic, retain) NSString * message;
- -(Id) initWithRequest :( NSURLRequest *) request;
- @ End
- //
- // RequestOperation. m
- // NSOperation
- //
- // Created by wangqiulei on 8/23/10.
- // Copy 2010 _ MyCompanyName _. All rights reserved.
- //
- # Import "RequestOperation. h"
- @ Implementation RequestOperation
- @ Synthesize message;
- -(Id) initWithRequest :( NSURLRequest *) request {
- If (self = [self init]) {
- _ Request = [request retain];
- _ Data = [[NSMutableData data] retain];
- }
- Return self;
- }
- -(Void) dealloc {
- [_ Request release];
- [_ Data release];
- [Super dealloc];
- }
- // If YES is returned, it indicates asychronously processing.
- -(BOOL) isConcurrent {
- Return YES;
- }
- // Start processing
- -(Void) start {
- If (! [Self isCancelled]) {
- NSLog (@ "% @", self. message );
- NSLog (@ "------------- % d", [self retainCount]);
- [NSURLConnection connectionWithRequest: _ request delegate: self];
- }
- }
- // Obtain data
- -(Void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {
- // Add data
- [_ Data appendData: data];
- NSLog (@ "% @", _ data );
- }
- // Http request ended
- -(Void) connectionDidFinishLoading :( NSURLConnection *) connection {
- }
- @ End
Summary:IPhone DevelopmentApplication in progressNSOperation MultithreadingI hope this article will be helpful to you!