Search code examples
objective-cuitableviewnstimerafhttprequestoperation

Time limit method in objective C


I have a networking method that request data from a server and then displaying it on the table view. But the problem is when the server is not responding or download takes too long I want to be able to just reload table view with data that is already acquired. I tried using performSelector:withObject:afterDelay: method but this method will perform selector even if download is finished. I tried creating a bool value to determine if download is already finished when selector is called but this will create overlap if download is already finished and then user did another networking action which the selector is not being called yet creating a false action because of this overlap. I want a method that does a time limit but can be canceled if the download already finished. what is the best way of implementing this? or is there a best way to do what I want?


Solution

  • It's possible to cancel your performSelector:withObject:afterDelay: call when the download finishes. For example, when the download finishes, you can call

    [NSObject cancelPreviousPerformRequestsWithTarget:selector:object:]
    

    Here, target is the object you called performSelector:withObject:afterDelay: on, selector is the selector you passed, object is the object you passed (or nil).


    Alternatively, if you only have one performSelector that would be running at a time, there is a simpler method you can use:

    [NSObject cancelPreviousPerformRequestsWithTarget:yourObject];
    

    yourObject will probably be self in this case.