2012-07-23 61 views
6

我試圖讓 - [的NSString stringWithContentsOfURL:編碼:錯誤:]異步的,由後臺線程運行它,synchronically:使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 2012-07-23 23:30:12

+0

首先,我認爲這將在主隊列上工作,因爲有['NSOperationQueue mainQueue]',但是我看到'sendAsynchronousRequest'。所以這不應該阻止UI更新。 – 2016-08-11 10:02:36

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); 
}