mk1*_*k12 10 iphone tail-recursion repeat nstimer
要重复一个方法调用(或消息发送,我猜适当的术语是)每x秒,是否更好地使用NSTimer(NSTimer的scheduledTimerWithTimeInterval:target:selector:userInfo:repeats :)或让该方法以递归方式调用自身结束(使用performSelector:withObject:afterDelay)?后者不使用对象,但可能不太清晰/可读?另外,为了让您了解我正在做什么,它只是一个带有标签的视图,倒计时到午夜12点,当它变为0时,它会闪烁时间(00:00:00)并永远发出哔哔声.
谢谢.
编辑:同样,重复播放SystemSoundID(永远)的最佳方法是什么?编辑:我最终使用它来永远播放SystemSoundID:
// Utilities.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioServices.h>
static void soundCompleted(SystemSoundID soundID, void *myself);
@interface Utilities : NSObject {
}
+ (SystemSoundID)createSystemSoundIDFromFile:(NSString *)fileName ofType:(NSString *)type;
+ (void)playAndRepeatSystemSoundID:(SystemSoundID)soundID;
+ (void)stopPlayingAndDisposeSystemSoundID;
@end
// Utilities.m
#import "Utilities.h"
static BOOL play;
static void soundCompleted(SystemSoundID soundID, void *interval) {
    if(play) {
        [NSThread sleepForTimeInterval:(NSTimeInterval)interval];
        AudioServicesPlaySystemSound(soundID);
    } else {
        AudioServicesRemoveSystemSoundCompletion(soundID);
        AudioServicesDisposeSystemSoundID(soundID);
    }
}
@implementation Utilities
+ (SystemSoundID)createSystemSoundIDFromFile:(NSString *)fileName ofType:(NSString *)type {
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:type];
    SystemSoundID soundID;
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
    return soundID;
}
+ (void)playAndRepeatSystemSoundID:(SystemSoundID)soundID interval:(NSTimeInterval)interval {
    play = YES
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL,
                                          soundCompleted, (void *)interval);
    AudioServicesPlaySystemSound(soundID);
}
+ (void)stopPlayingAndDisposeSystemSoundID {
    play = NO
}
@end
似乎工作正常..对于标签闪烁我会使用NSTimer我猜.
计时器更适合严格定义的间隔.如果你的函数调用本身有一个延迟,你将失去准确性,因为它没有真正同步到一个时间间隔.总是有时间运行实际的方法本身,这使得间隔出来.
坚持使用NSTimer,我会说.
| 归档时间: | 
 | 
| 查看次数: | 7474 次 | 
| 最近记录: |