要每隔x秒重复一次方法调用(或消息发送,我猜合适的术语是),最好是使用NSTimer (NSTimer的NSTimer),还是让该方法在末尾递归地调用自己(使用性能选择器: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。
发布于 2009-09-29 00:48:12
定时器更适合于严格定义的间隔。如果您的函数调用本身有一个延迟,您将失去准确性,因为它没有真正同步到一个时间间隔。运行实际方法本身所需的时间总是很长,这就导致了间隔的延长。
我会说,坚持使用NSTimer。
发布于 2009-09-29 04:57:14
为了给其他答案添加一点,递归调用的情况是,调用可能需要未知的时间--假设您正在用少量的数据反复调用web服务,直到完成为止。每个调用可能需要一些未知的时间,所以在web调用返回之前,代码什么也不做,然后下一批将被发送出去,直到没有更多的数据需要发送,并且代码不会再次调用自己。
发布于 2009-09-29 01:52:46
由于应用程序依赖于时间的准确性(即它需要每秒执行一次),所以NSTimer会更好。该方法本身需要一段时间才能执行,如果每秒钟调用一次,那么NSTimer就可以了(只要您的方法不超过1秒)。
要重复播放您的声音,可以设置一个完成回调并在那里重放声音:
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];
}https://stackoverflow.com/questions/1490028
复制相似问题