2017-03-23 43 views
1

我想在AppDelegateapplicationWillResignActive函數中調用ViewController的成員函數。不知道這樣做的最佳方式是什麼。我試圖這樣做:從AppDelegate調用ViewController的成員函數

let landmark = LandmarkViewController() 
landmark.test() 

但它似乎不正確。我基本上是創建控制器的新實例,而不是使用已經存在的實例。

+1

這可能是通過[通知中心]發送通知的好地方(https://developer.apple.com/reference/foundation/nsnotificationcenter)。你的'LandmarkViewController'可以是一個觀察者。 – hola

+0

你在使用故事板嗎?如果是的話,這是你尋找什麼:) [回答](http://stackoverflow.com/questions/41136597/create-single-of-a-viewcontroller-in-swift-3/41136939#41136939) –

回答

6

我認爲最好的方法來實現你想要的是設置一個觀察者通知UIApplicationWillResignActiveNotification到你的視圖控制器本身。

override func viewDidLoad() { 
    super.viewDidLoad() 
    let notificationCenter = NotificationCenter.default 
    notificationCenter.addObserver(self, selector: #selector(appDidResign), name: Notification.Name.UIApplicationWillResignActive, object: nil) 
} 

func appDidResign() { 
    // do your stuff 
} 

deinit { 
    NotificationCenter.default.removeObserver(self) //always remember to remove any observers (you can do this in deinit in this case) 
} 
+0

嗯,我認爲這不是OP所要求的,無論如何它可能是一個咕approach的方法...... –

+0

這是真的。雖然我認爲OP在問這是因爲沒有意識到通知:) – tanzolone

+0

我建議還要 - 添加與發佈通知相關的代碼。 –

0

是的,你的上面的代碼將創建一個新的實例。如果你想使用現有的實例,那麼你需要以某種方式獲得對現有實例的引用。

如何獲得參考將取決於您如何設置視圖控制器。例如,如果您的LandmarkViewController是根視圖控制器,則可以通過UIWindow獲取它。或者,當您創建實例時,您可以將對視圖控制器的引用傳遞給應用程序委託。這一切都取決於你的應用程序的設置。

+0

這應該是一個評論 –

+0

爲什麼它應該是一個評論?我正在回答他的問題:) – Fahim

0

您可以從UIWindow得到rootViewController(這你LandmarkViewController是我如何理解):

if let rootViewController = self.window?.rootViewController as LandmarkViewController { 
    rootViewController.test() 

} 
0

我認爲最好的辦法就是在這個類中添加觀察員通知。 有些人認爲這樣的:

class LandmarkViewController: ... 
{ 
    ... 
    func viewDidLoad() 
    { 
     ... 
     NotificationCenter.default.addObserver(forName: applicationWillResignActive, object: nil, queue: OperationQueue.main) { (notification) in 
      ... 
     } 
    } 
}