要每x秒重复一次方法调用(或消息发送,我想合适的术语是),最好使用 NSTimer(NSTimer 的 scheduleTimerWithTimeInterval:target:selector:userInfo:repeats:) 还是让该方法在结束(使用 performSelector:withObject:afterDelay)?后者不使用对象,但可能不太清晰/可读?另外,只是为了让您了解我在做什么,它只是一个带有标签的视图,该标签倒计时到午夜 12:00,当它到达 0 时,它会闪烁时间 (00:00:00)并永远播放哔声。
谢谢。
编辑:另外,重复播放 SystemSoundID (forever) 的最佳方式是什么?编辑:我最终使用它来永远播放 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。