2013-05-05 105 views
0

我想弄清楚Objective-C中的異常處理是如何工作的。所以我通過執行一個不存在的選擇器(繁榮)來強制例外。當我運行它時,應用程序崩潰,異常處理不當。有人可以向我展示在objective-c中處理異常的正確方法嗎?Objective-C異常處理

@try{ 
     [self performSelector:@selector(boom)]; 
    } 
    @catch (NSException *ex) { 
     NSLog(@"Error"); 
    } 

...還有人可以告訴我如何處理下面的代碼異常。我爲四種不同的音效使用了一個實例變量。播放後,我將該變量設置爲零。出於某種原因,下面的代碼有時會壓碎應用程序,所以我想處理該異常。謝謝。如果從按下按鈕事件調用- (void) playSound:(NSUInteger) number withDelay:(NSTimeInterval) delay

- (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]; 
     } 
    } 
} 
+3

注意,這是不相關的Xcode。你可以使用任何IDE,任何編譯器,無論如何 - 問題是關於** Objective-C **異常。 – 2013-05-05 05:09:24

+0

向我們展示上面代碼拋出異常 – JustSid 2013-05-05 05:13:38

+0

的代碼,我可以在哪裏放置拋出,然後嘗試捕獲? – Stoner 2013-05-05 05:17:30

回答

2

異常處理不會解決在這裏你的問題,

多個按鈕按下會導致這種崩潰。由於您使用的是相同的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);