下面是每個請求的簡單示例。
在我的應用程序中,我使用音頻播放器來傳輸遠程音頻文件。和一個UITabBarController
舉行並提出我的看法。我在我的SongsViewController
中有歌曲的桌面視圖。當一行被點擊時,有兩件事發生...... 1)用戶界面延伸到一個新的視圖控制器,我的NowPlayingViewController
和2)撥打我的ControllerClass
,它處理從指定的URL獲取歌曲,並開始播放。我需要我的ControllerClass
的代表爲NowPlayingViewController
,這樣當歌曲完成加載時,我可以發送更新到NowPlayingViewController
上的UI。所以,裏面的SongsViewController
我這樣做的didSelectRowAtIndexPathMethod
...
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//get a reference to the NowPlayingViewController, and set it as the delegate to the ControllerClass
let nowPlayingVC = NowPlayingViewController()
ControllerClass.delegate = nowPlayingVC
self.tabBarController.selectedIndex = 1
}
BUT!當ControllerClass
執行其代表回撥到NowPlayingVC
時,UI上沒有任何事情發生!在我的頭撞在牆上後...我發現原因不起作用是因爲: 當一首歌被點擊時,標籤欄控制器正在呈現一個NowPlayingViewController
的實例,它已經有一個引用。當一首歌被點擊時,我還會抓住另一個參考NowPlayingViewController
,然後我使用該實例(參考)設置爲我的ControllerClass
的代表。這是一個問題,因爲我的標籤欄控制器所保存的NowPlayingViewController
的實例是NowPlayingViewController
的不同實例,而不是我引用並設置爲我的ControllerClass
的代理的實例。這意味着當ControllerClass
去回調到NowPlayingViewController
時,它會回調到與標籤欄控制器提供的實例不同的實例!因此,我沒有看到像他們應該發生的任何UI變化。
在我的情況下,因爲我使用的是UITabBarController
我能夠做到這一點......
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//find the instance of the NowPlayingViewController that is being presented, the one that i am VIEWING and set that instacne as the delegate to the ControllerCLass
let nowPlayingVC = self.tabBarController?.viewControllers![1] as! NowPlayingVC
ControllerClass.delegate = nowPlayingVC
}
通過訪問被保持的標籤欄內,該視圖控制器,我能夠抓住到NowPlayingViewController
這是正被呈現的一個,並且因此ControllerClass
,在調用的相同的實例的引用回到它的代表,正確地回撥到由標籤欄控制器呈現的NowPlayingViewController
的實例。
我假設你沒有使用UITabBarController,但你的解決方案仍然是引用你的VC的SAME實例,並確保在這兩個地方使用這個實例!只要確保引用SAME實例。
您需要顯示一些代碼;看起來你沒有保持對視圖控制器實例的正確引用。 – Paulw11
@ Paulw11呃哦,我應該保留一些第一個參考? – simplexity
視圖控制器與數組或字典或任何其他對象沒有區別。你可以有多個實例,你需要在適合iOS的短時間內參考合適的實例 – Paulw11