Aleksandrs Muravjovs
Aleksandrs Muravjovs

Reputation: 173

Overriden method not being called

I have a problem that I can't override function.

My parent class below:

class A: UIViewController {

 func parentalGate() {

        let appearance = SCLAlertView.SCLAppearance(
            kTitleFont: UIFont(name: "Futura", size: 20)!,
            kTextFont: UIFont(name: "Futura", size: 14)!,
            kButtonFont: UIFont(name: "Futura", size: 14)!,
            showCloseButton: false
        )
        let alert = SCLAlertView(appearance: appearance)
        let alert2 = SCLAlertView(appearance: appearance)

        if (UserDefaults.standard.object(forKey: "language") as? String == "english") {

            let txt = alert.addTextField("Enter third letter")

            alert.addButton("Done") {

                if ((txt.text == "P") || (txt.text == "p")) {

                    self.parentalGatefunctions()
                } else {
                    alert2.addButton("Close", target: SCLAlertView(), selector: #selector(SCLAlertView.hideView))
                    alert2.showError("Incorrect letter entered", subTitle: "Try again")
                }
            }

            alert.addButton("Close", target: SCLAlertView(), selector: #selector(SCLAlertView.hideView))

            alert.showWarning("We need to be sure that You are an adult", subTitle: "Enter the third letter of word: HAPPY")

        }
}

func parentalGatefunctions(){

        // Parental gate functions are overriten in classes where they are used for
    }

}

Child class below:

class B: A {


    @IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {

        A().parentalGate()
    }

    override func parentalGatefunctions() {

        print ("Do something in class B")
    }
}

Another class:

class C: A {


    @IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {

        A().parentalGate()
    }

    override func parentalGatefunctions() {

        print ("Do something in class C")
    }

}

All the time when parentalGate() method is called in classes B and C only empty parentalGateFunctions() is called without the overriten methods are not called in classes.

Am I doing something wrong? I just want to avoid repetitive code in my classes.

Thanks!

Upvotes: 0

Views: 272

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Your mistake is here.

@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
    A().parentalGate()
}

Since you already have subclassed A, that method is available to you. So, just call the method in your subclass rather than the one in a new instance of the superclass! (which would obviously call the empty method)

@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
    parentalGate()
}

Upvotes: 4

Related Questions