objective-c 中后台线程中的重复方法是否正确?

Is recurring method in background thread correct way in objective-c?

我正在尝试以下代码,我在后台线程中从服务器加载文件。如果它加载失败然后再次调用相同的方法,这是在后台线程中再次调用它的正确方法吗?

[self performSelectorInBackground:@selector(loadFileFromServer:) withObject:nil];

int retryCount = 0;

- (void)loadFileFromServer{
     FetchServerFile *fetchF = [FetchServerFile new];
     [fetchF fetchFile:^(BOOL OK){
      if(OK){
         [self toStart];
      }
      else{
         retryCount++;
         if(retryCount<3){
             [self performSelectorInBackground:@selector(loadFileFromServer:) withObject:nil];
         }
         else{
             [self exitLogic];
         }
      }
     }];
}

关于performselectorinbackground:withObject:的使用,the documentation告诉我们:

This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program. For more information about how to configure and run threads, see Threading Programming Guide.

如果您想在后台线程上 运行 一些代码,使用 Grand Central Dispatch 会更容易(也更有效)。

话虽这么说,但它引出了一个问题,你为什么要把它推到后台线程。网络代码通常 运行 是异步的,在这种情况下 运行 在后台线程上运行此代码没有什么意义。这只会使情况复杂化。

关于重试逻辑的细节,这取决于目的。如果用户未连接到网络,某些应用程序会使用其中一个“可达性”库来主动警告用户,但在这种情况下,您本身不会使用重试逻辑,而只是拥有一个处理程序网络重新建立后调用。

似乎重试逻辑必须合并到请求的末尾(您正在检查请求是否成功),而不是在开始时,即您发起请求的地方。

此外,如果您只是尝试执行一些简单的上传和下载,您可能需要考虑使用后台 URLSessionConfiguration,因为它可以处理各种各样的问题(例如连接问题、用户离开upload/download 完成之前的应用程序,等等)。