iPhone dev — performSelector:withObject:afterDelay or NSTimer?

后端 未结 3 1078
小蘑菇
小蘑菇 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: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];
    }
    

提交回复
热议问题