简体   繁体   中英

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

I am trying the following code, where I am loading a file from the server in the background thread. And if it failed to load then again calling the same method, is this the right way to call it again in the background thread?

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

Regarding the use of performselectorinbackground:withObject: , the documentation tells us:

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 .

It's much easier (and more efficient) to just use Grand Central Dispatch if you want to run some code on a background thread.

That having been said, it begs the question why you're pushing this to a background thread at all. Network code generally runs asynchronously, in which case there's little point to running this code on a background thread. It will only complicate the situation.

Regarding the specifics of the retry logic, it depends upon the purpose. Some apps use one of the “reachability” libraries to proactively warn user if they're not connected to the network, but in this case you wouldn't use retry logic, per se, but rather you'd just have a handler that is called once the network is re-established.

It also seems that the retry logic must be incorporated at the end of a request (where you're checking to see if the request was successful), not at the start, where you initiate the request.

Also, if you're just trying to perform some simple uploads and downloads, you might want to consider using the background URLSessionConfiguration , as that handles a whole variety of issues (eg connectivity issues, user leaves app before upload/download is done, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM