搜尋此網誌

工商服務

2013年9月26日 星期四

[改版秘技]隨著 iOS 版本更迭,如何呼叫正確版本的 API 函式?

↑警告訊息指出所使用的特定 API 從 iOS 6 版本開始就已經不再建議使用了。

隨著 iOS 版本更迭,基於更能夠符合開發者所需以及追求更好的效率等理由,有些 API 也會跟著與時俱進,於是官方文件甚至是 Xcode 開發工具都會提醒你,有些 API 已經不宜也不建議再使用了(英文會用「 deprecated 」這個字眼),而就算使用了也不會立即導致 App 發生錯誤,但是並不能保證在未來那些 deprecated API 不會被取消並移除,所以官方文件和 Xcode 開發工具一方面想要提醒開發者已經有改良版的替代性 API 可供使用了,另一方面也是想要鼓勵開發者趕緊加快採用新版 API 的腳步。至於正確的替代性 API 是哪些,則可以在官方文件和 deprecated API 的表頭檔註解中看到。

舉例而言,喚起另一個 ViewController 到前景,然後把本來正在檢視的 ViewController 蓋住的 API ,原本是 presentModalViewController ,但是在 iOS 6 之後就被 presentViewController 給取代了。於是當我們在 Xcode 4.6.3 中開發適用於 iOS 6.1 的 App 時,便會在 Xcode 的編輯區中看到黃色三角形驚嘆號的警告提示,指出「 'presentModalViewController:animated:' is deprecated: first deprecated in iOS 6.0 」。

至於哪個新版 API 才是替代品呢?按住 command 鍵然後以滑鼠游標點擊 Xcode 編輯區中出現底線超連結模樣的 presentModalViewController 字眼,這樣就可以在表頭檔中看到替代品是 presentViewController 。下列是擷取自 UIKit.framework 的 UIViewController.h 表頭檔的內容:

// Display another view controller as a modal child. Uses a vertical sheet transition if animated.This method has been replaced by presentViewController:animated:completion:

- (void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated NS_DEPRECATED_IOS(2_0, 6_0);

但是如果在開發 iOS 6 App 的時候,也想要同時回溯支援前一代的 iOS 5 ,那麼就必須想辦法讓新舊 API 能夠和平共處,並且在每次都呼叫到正確的 API 版本。解決方法就是在呼叫這些 API 之前,先透過 respondsToSelector 來測試是否存在新版的 API ,也就是說如果不存在的話,就改成呼叫原先舊版的 iOS SDK 能夠支援的那個 API 。示範如下:

if ([self respondsToSelector:@selector(presentViewController:animated:completion:)])
  [self presentViewController:theViewController animated:YES completion:nil];
else
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  [self presentModalViewController:theViewController animated:YES];
#pragma clang diagnostic pop

在上面的程式碼中,使用的 #pragma 是為了抑制 Xcode 的編輯器,不要讓它在看到 deprecated API 的時候又跑出黃色三角形驚嘆號的警告提示來了。

PS:在官方 2010 年出版的《 SDK Compatibility Guide 》線上文件裡面,就有一個小節叫做〈 Finding Instances of Deprecated API Usage 〉(找出使用了舊版 API 的實體)是在講這件事。

【奇步學習分級:中級】

───
奇步應用的臉書粉絲專頁經常分享新知趣聞,歡迎加入追蹤。

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...