簡體   English   中英

從任何ViewController訪問類變量

[英]Access class variable from any ViewController

我的應用程序具有以下結構:

  • 我有一個存儲多個Patient()的Realm數據庫。

  • 具有兩個子級的TabViewControllerSearchViewControllerDetailViewController

  • SearchViewController中有一個TableView

  • :在TableView中,並將其存儲在這個變量中的一樣SearchViewController -我倍數患者之間進行選擇- 病人() var chosenPatient = ChosenPatient()

類ChosenPatient來自ModelController:

class ChosenPatient: NSObject {
    var data = Patient()
    { ... multiple functions ... }    
}

我需要在SearchViewController的updateLabels()中訪問以下內容:

label.stringValue = chosenPatient.data.name/lastName/age etc

但是我想在我的DetailsViewController中做同樣的事情。 我只想簡單地擁有一個函數updateLabels(),該函數可以檢索我在SearchViewController中選擇的相同患者並訪問該患者擁有的所有信息。

我已經閱讀了有關NSNotifications,Delegates和Segues的信息,但找不到適合於我的應用程序方案的好的解釋方法。

我想要一個具有唯一的Patient()的GLOBAL變量,並以一種簡單明了的方式從任何ViewController訪問Patient.data。

問候 :)

[使用適用於macOS的XCODE 8.3,swift 3.2,應用程序]

如果是一對一的關系,我通常會使用協議代理模式。 除非絕對必要,否則您不希望將任何變量都保留為全局變量。

為您的UITabBarController一個自定義類,然后將SearchViewController分配給DetailViewController數據源。

protocol ChosenPatientDataSource: class {
    var chosenPatient: ChoosenPatient { get }
}

class SearchViewController: UITableViewController, ChosenPatientDataSource {
    var chosenPatient = ChosenPatient()
}

class DetailViewController: UIViewController {
    weak var dataSource: ChosenPatientDataSource?

    func useChosenPatient() {
        let chosenPatient = dataSource?.chosenPatient
        ...
    }
}

希望對您有所幫助!

為了在不同選項卡(例如SearchViewControllerDetailViewController視圖之間傳遞信息,我將使用NSNotification

我強烈反對用大量通知填充您的應用程序的誘惑,因為它很快會使代碼很難理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM