[英]Objective-C exception handling
我试图弄清楚Objective-C中的异常处理是如何工作的。 所以我通过执行一个不存在的选择器(繁荣)来强制执行异常。 当我运行它时,应用程序崩溃,异常处理不当。 有人能告诉我在objective-c中处理异常的正确方法吗?
@try{
[self performSelector:@selector(boom)];
}
@catch (NSException *ex) {
NSLog(@"Error");
}
...有人还可以告诉我如何处理下面代码的异常。 我正在使用一个实例变量来实现四种不同的声音效果。 播放后,我将变量设置为nil。 出于某种原因,下面的代码有时会破坏应用程序,所以我想处理该异常。 谢谢。
- (void) playSound:(NSUInteger) number withDelay:(NSTimeInterval) delay
{
if(sound == nil)
{
NSURL* url;
switch (number)
{
case 1: url = [[NSBundle mainBundle] URLForResource:@"Shuffle" withExtension:@"caf"]; break;
case 3: url = [[NSBundle mainBundle] URLForResource:@"Clap" withExtension:@"caf"]; break;
case 4: url = [[NSBundle mainBundle] URLForResource:@"Glass" withExtension:@"caf"]; break;
case 5: url = [[NSBundle mainBundle] URLForResource:@"Knock" withExtension:@"caf"]; break;
default: break;
}
if (url != nil)
{
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[sound setCurrentTime:0];
[sound prepareToPlay];
[sound setVolume:1.0];
[sound performSelector:@selector(play) withObject:nil afterDelay: delay];
}
}
}
异常处理不会解决您的问题,
如果你调用- (void) playSound:(NSUInteger) number withDelay:(NSTimeInterval) delay
按钮按下事件。 按下多个按钮会导致这种崩溃。 因为您正在使用相同的AVAudioPlayer变量*声音 ,并且相同的对象用于在延迟后播放声音。来自其他按钮的呼叫可以启动声音播放器,而另一个尝试播放声音。
如果这些是短声音片段(少于30秒),不使用AVAudioPlayer
,最好使用AudioServicesPlaySystemSound
,
您可以编写一种延迟播放开始的方法,这样可以让您同时播放多个声音片段而不会出现任何问题。
NSString *path = [[NSBundle mainBundle] pathForResource:@"Shuffle" ofType:@"caf"];
NSURL *url = [NSURL fileURLWithPath:path];
SystemSoundID soundFileObject;
AudioServicesCreateSystemSoundID ((__bridge_retained CFURLRef) url, &soundFileObject);
AudioServicesPlaySystemSound (soundFileObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.