简体   繁体   中英

calling protocol method that is implemented by subclass from the superclass

I have multiple TableViewController classes that inherit from a basic TableViewController class like this:

class BasicTableViewController: UITableViewController {
}

class SpecificTableViewController: BasicTableViewController {
}

class AnotherSpecificTableViewController: BasicTableViewController {
}

then i created a very simple protocol to add refreshing capabilities to the specific viewcontroller classes like this:

@objc
protocol Refreshable {
    func refresh()
}

my specific viewcontroller classes can implement the protocol like this:

class SpecificTableViewController: BasicTableViewController, Refreshable {
    func refresh() {
        getSomeDataFromServer()
    }
}

the question now is: what is the correct way to call the refresh method from the BasicTableViewController which itself does not conform to the Refreshable protocol? right now i am doing something like this (without being sure if it's the way to go):

class BasicTableViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        if let _ = self as? Refreshable {
            let refreshControl = UIRefreshControl()
            refreshControl.addTarget(self, action: #selector(Refreshable.refresh), forControlEvents: .ValueChanged)
            self.refreshControl = refreshControl
        }
    }
}

at the very beginning i did not mark the protocol with @objc and tried to build the selector like this: #selector(refresh) . that did not work though. hope to get some clarification. :)

thanks in advance!

I would let the Superclass implement the Refreshable protocol

protocol Refreshable {
    func refresh()
    func shouldBeRefreshable() -> Bool
}

//Making the protocol methods optional
extension Refreshable {
    func refresh() {}
    func shouldBeRefreshable() -> Bool { return false}
}

class SuperView: Refreshable {
    func addRefreshControl() {
        if shouldBeRefreshable() {
            //Add Refresh Control
        }else {
            // Do Nothing
        }
    }

    func shouldBeRefreshable() -> Bool {
        //default
        return false
    }
}

//Refreshable Class
class ChildA: SuperView {
   func refresh() {
        print("Refresh in Child A")
    }
    override func shouldBeRefreshable() -> Bool {
        return true
    }
}

//Not Refreshable Class
class ChildB: SuperView {
}

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