iPhone dev — performSelector:withObject:afterDelay or NSTimer?

后端 未结 3 1087
小蘑菇
小蘑菇 2021-02-14 10:06

To repeat a method call (or message send, I guess the appropriate term is) every x seconds, is it better to use an NSTimer (NSTimer\'s scheduledTimerWithTimeInterval:ta

相关标签:
3条回答
  • 2021-02-14 10:16

    Just to add a bit to the other answers, the case for a recursive call would be when the call might take an unknown amount of time - say you are calling a web service repeatedly with small amounts of data until you are finished. Each call may take some unknown amount of time so you have the code do nothing until the web call returns, then the next batch is sent out until no more data remains to be sent and the code does not call itself again.

    0 讨论(0)
  • 2021-02-14 10:20

    A timer is more suited to a strictly defined interval. You will lose accuracy if you have your function call itself with a delay because its not really synced to a time interval. There's always the time taken to run the actual method itself as well which puts the interval out.

    Stick with an NSTimer, I'd say.

    0 讨论(0)
  • 2021-02-14 10:26

    Since your application depends on time accuracy (i.e. it needs to execute once per second), the NSTimer would be better. It takes some time for the method itself to execute, and an NSTimer would be fine with that (as long as your method takes less than 1 second, if it's called every second).

    To repeatedly play your sound, you can set a completion callback and replay the sound there:

    SystemSoundID tickingSound;
    
    ...
    
    AudioServicesAddSystemSoundCompletion(tickingSound, NULL, NULL, completionCallback, (void*) self);
    
    ...
    
    static void completionCallback(SystemSoundID mySSID, void* myself) {
      NSLog(@"completionCallback");
    
      // You can use this when/if you want to remove the completion callback
      //AudioServicesRemoveSystemSoundCompletion(mySSID);
    
      // myself is the object that called set the callback, because we set it up that way above
      // Cast it to whatever object that is (e.g. MyViewController, in this case)
      [(MyViewController *)myself playSound:mySSID];
    }
    
    0 讨论(0)
提交回复
热议问题