1

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?

samitarmum
  • 83
  • 8
  • 1
    Show your code, please. The answer depends entirely on the details of _how_ you are doing this data request. – matt Jan 09 '16 at 16:11
  • Regarding *overlap* issue, you can create and share NSMutableArray for each job and insert any value (e.g. `@""`) into it on "job finished" or whatever event you want. NSMutableArray is thread-safe by default, iirc (you should check that to be sure). – user3125367 Jan 09 '16 at 16:11
  • `NSMutableArray` is **not** thread safe. – Avi Jan 09 '16 at 16:15
  • I did not remember correctly then :) – user3125367 Jan 09 '16 at 16:19
  • I need all the data because it is used to calculate cell height. kinda like twitter feeds need to be downloaded to calculate label height in cell. – samitarmum Jan 09 '16 at 16:29

2 Answers2

2

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.

Ben Kane
  • 9,331
  • 6
  • 36
  • 58
-1

It sounds like you're looking for NSTimer. You can start a deadline timer when your network activity begins, and invalidate the timer if the work finishes before the timer fires.

lemnar
  • 4,063
  • 1
  • 32
  • 44
  • imagine this, an nstimer is initiated -> download begins and then finished but the timer has not yet reached its limit -> another download begins ->while the download is happening the previous nstimer just reached its limit -> reloading table while all the data is not yet finished downloaded even though it is just happened 1 second before. – samitarmum Jan 09 '16 at 16:34