简体   繁体   中英

Accessing ViewController class from another class in Swift

I'm new in iOS development,

I have and "API Helper" Swift class that gets some data as a JSON array. And when the array is ready I want to call a method in my MasterViewController to update the tableView with the data.

I tried to do like that:

var facilities : [Facility]? {
        didSet {

            MasterViewController().facilitiesLoaded()
        }
    }

And then reload the tableView but without seeing anything.

I think the problem is that I'm creating a new instance of the ViewController, but what I should have is to get access to the current instance of the class.

Any idea, or a better design? Thanks..

If this "facilities" variable is instance of MasterViewController then do :

var facilities : [Facility]? {
didSet {
        self.facilitiesLoaded()
    }
}

Thanks to @dcestari,

I did added callback blocks to the API call and handled it in the ViewController and that did the trick

In API caller method:

func loadFacilities(completionHandler:(() -> Void!)) {
    // do stuff
    completionHander()
}

In the ViewController:

func getFacilities() {
        api.loadFacilities({
             // update tableView
        })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM