MyViewController *sampleViewController = [[[MyViewController alloc]initWithXXX] autorelease]; [self.navigationController pushViewController: sampleViewController animated:true];
BUG:介面無反應。
可能出錯的原因分析:
1:self.navigationController 為 nil,空指標執行 pushViewController 直接跳過,接著 sampleViewController 會被釋放,所以介面無反應。
self.navigationController 為什麼會是空呢?navigationController 是從 UIViewController 父類繼承來的屬性,不是隨便都能用的——除非你當前的 viewController 是被 nav push 進來的,或用 xib/程式碼做成了 navigationController 的 root,cocoa 才會給它賦值。(題外話:我很多介面只是局部用到某個 ViewController,這種情況該 viewController 的 nav 為空,若要正確使用,可以從 app 取、自己賦值、或整體介面取,方式隨你)
2、self.navigationController 為 nil,介面掛了。
如果你 sampleViewController 用到了網路異步請求,在 initWithXXX 的時候會去取數,那你十有八九會掛掉。原因:大家網路請求經常如下:
TwitterClient *twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(XXXReceive:obj:)]; [twitterClient getXXX:param];
恭喜你,這種情況不管 navigationController 是否為空,程式都極容易掛掉。原因是網路請求我們都用異步方式拉取數據,當數據回來後會回呼到本類的 XXXReceive:obj 方法,但如果介面已退出、數據才收到會如何?那就不是空指標調用了——TwitterClient 裡記錄的需要回呼的內存地址上什麼情況都有可能,回呼……杯具了。
解法:把 twitterClient 做成成員,在析構時該怎麼收拾就怎麼收拾一下。
3、self.navigationController 為 nil,介面掛了。
和上文一樣,twitterClient 已做成成員、dealloc 也清理了現場,還是會掛。原因:異步問題——twitterClient 已經取到數據,但 sampleViewController 已被釋放,而 dealloc 根本來不及進來……
解法:1、確保 nav 正確;2、盡量在介面 viewDidLoad 時發起網路請求,在 disappear 時清理網路。
reason: 'Pushing a navigation controller is not supported'
報這個錯誤的原因是:大家知道可以將 ViewController push 到一個 NavigationController 中,就像入棧操作。但當把一個 NavigationController 再次 push 到另一個 NavigationController 中時,就會報 'Pushing a navigation controller is not supported' 的錯誤——NavigationController 不支援 push 進來的物件是 NavigationController。
修改方法:將要進入的頁面不去繼承 UINavigationController。
有時候項目裡會有一種消息推送,就是彈出提示用戶消息,而消息中帶有鏈接,當你點擊鏈接時不能跳轉。這種情況是因為你的 self.navigationController = nil 造成的——因為你彈窗的那個控制器沒有用 UINavigationController 包裝。
以上便是 iOS 開發中 UINavigationController 常見問題的原因分析,希望對大家有所幫助。