我试图弄清楚异常处理在Objective-C中是如何工作的。所以我通过执行一个不存在的选择器(boom)来强制异常。当我运行它时,应用程序崩溃了,异常没有得到正确处理。有人可以告诉我在objective-c中处理异常的正确方法吗?
@try{
[self performSelector:@selector(boom)];
}
@catch (NSException *ex) {
NSLog(@"Error");
}
...并且有人也可以告诉我如何处理下面代码的异常。我将一个实例变量用于四种不同的音效。播放后,我将变量设置为零。出于某种原因,下面的代码有时会破坏应用程序,因此我想处理该异常。谢谢。
- (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];
}
}
}