2012年3月7日 星期三

非同步網路探究

NSURLConnection:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
                          queue:(NSOperationQueue*) queue
              completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler
->
When the request has completed or failed, the block will be executed from the context of the
specified NSOperationQueue

ex:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue 
                           completionHandler:^(NSURLResponse *response,    
                                    NSData *data, NSError *error) 
 {
         NSLog(@"thread %p %p", [NSThread currentThread], [NSThread mainThread]);
}];
->   currentThread != mainThread

NSOperationQueue *queue = [NSOperationQueue currentQueue];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue 
                           completionHandler:^(NSURLResponse *response,    
                                    NSData *data, NSError *error) 
 {
         NSLog(@"thread %p %p", [NSThread currentThread], [NSThread mainThread]);
}];
->   currentThread == mainThread

block和物件生命的關係:


假設呼叫以下method


 [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

}];
如果block裡帶有某個物件,則此物件將維持生命直到block執行完。











沒有留言:

張貼留言