2012-07-23 11 views
6

私が作るしようとした - [NSStringのstringWithContentsOfURL:エンコーディング:エラー:]非同期に、バックグラウンドスレッドから、同期的にそれを実行することによって:stringWithContentsOfURLを非同期にする - 安全ですか?

__block NSString *result; 
dispatch_queue_t currentQueue = dispatch_get_current_queue(); 

void (^doneBlock)(void) = ^{ 
    printf("done! %s",[result UTF8String]); 
}; 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 
             (unsigned long)NULL), ^(void) { 
    result = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/"] encoding:NSUTF8StringEncoding error:nil]; 
    dispatch_sync(currentQueue, ^{ 
     doneBlock(); 
    }); 
}); 

正常に動作し、その、そして最も重要なのは、その非同期。

これを行うのが安全かどうか、またはスレッドの問題などがありますか?

ありがとうございます。

答えて

27

これは安全なはずですが、なぜホイールを再発明するのですか?

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; 
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    // etc 
}]; 
+0

歓声!私はこれが可能であることを知りませんでした:P – JonasG

+0

最初に私は 'NSOperationQueue mainQueue 'のためにメインキューで動作しますが、' sendAsynchronousRequest'を見ました。これで、UIが更新されるのを止めるべきではありません。 –

0

また、使用することができます。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

dispatch_async(queue, ^{ 
     NSError *error = nil; 
     NSString *searchResultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:searchURL] 
                  encoding:NSUTF8StringEncoding 
                   error:&error]; 
     if (error != nil) { 
      completionBlock(term,nil,error); 
     } 
     else 
     { 
      // Parse the JSON Response 
      NSData *jsonData = [searchResultString dataUsingEncoding:NSUTF8StringEncoding]; 
      NSDictionary *searchResultsDict = [NSJSONSerialization JSONObjectWithData:jsonData 
                       options:kNilOptions 
                       error:&error]; 
      if(error != nil) 
      { 
       completionBlock(term,nil,error); 
      } 
      else 
      { 

       //Other Work here 
      } 
     } 
    }); 

しかし、はい、それは安全でなければなりません。私は、代わりにNSURLConnectionを使用するように言われてきましたが、エラーコールなどのために、インターネット経由で通信するときなどです。私はまだこれについて研究しています。

0
-(void)loadappdetails:(NSString*)appid { 
    NSString* searchurl = [@"https://itunes.apple.com/lookup?id=" stringByAppendingString:appid]; 

    [self performSelectorInBackground:@selector(asyncload:) withObject:searchurl]; 

} 
-(void)asyncload:(NSString*)searchurl { 
    NSURL* url = [NSURL URLWithString:searchurl]; 
    NSError* error = nil; 
    NSString* str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; 
    if (error != nil) { 
     NSLog(@"Error: %@", error); 
    } 
    NSLog(@"str: %@", str); 
} 
関連する問題