在 iOS 5.0 前後,presentViewController 相關的呼叫方法參數有所變動。若在 5.0 之後的環境使用新方法,會無法在舊版本上執行;而舊版本的呼叫方法,Apple 又已不再建議使用。這裡提供一種能同時相容高低版本的通用寫法。
AboutViewController *mAboutViewController = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]) {
[self.navigationController presentViewController:mAboutViewController animated:YES completion:nil];
}else{
[self.navigationController presentModalViewController:mAboutViewController animated:YES];
}
[mAboutViewController release];
mAboutViewController = nil;
同理,dismiss 時也可用類似寫法:
if ([self respondsToSelector:@selector(dismissViewControllerAnimated:completion:)]) {
[self dismissViewControllerAnimated:YES completion:nil];
}else{
[self dismissModalViewControllerAnimated:YES];
}
核心技巧是:在呼叫前先用 respondsToSelector: 判斷目前系統是否支援新的 API。若支援就呼叫高版本方法,否則退回使用低版本方法。以此類推,日後遇到 Apple 高版本 SDK 不再支援某些低版本 API 時,都能用同樣的判斷來解決高低版本的相容問題。