【问题标题】:Making stringWithContentsOfURL asynchronous - Is it safe?使 stringWithContentsOfURL 异步 - 安全吗?
【发布时间】:2012-07-22 04:54:40
【问题描述】:

我试图通过从后台线程异步运行 -[NSString stringWithContentsOfURL:encoding:error:] 来实现异步:

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

它工作正常,最重要的是它是异步的。

我的问题是这样做是否安全,或者是否存在任何线程问题等?

提前致谢:)

【问题讨论】:

    标签: objective-c ios asynchronous thread-safety http-request


    【解决方案1】:

    这应该是安全的,但为什么要重新发明轮子呢?

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

    【讨论】:

    • 首先我虽然因为[NSOperationQueue mainQueue],这将在主队列上工作,但我看到sendAsynchronousRequest。所以这不应该阻止 UI 更新。
    【解决方案2】:

    你也可以使用:

    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 代替,因为错误调用等通过互联网通信时。我还在做这方面的研究。

    【讨论】:

      【解决方案3】:
      -(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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-16
        • 2019-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多