Created
December 13, 2022 10:40
-
-
Save tgnivekucn/1040e7ad3a044bb0fe32b86583b1cf67 to your computer and use it in GitHub Desktop.
Call a method from a String in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ref: https://stackoverflow.com/questions/24245262/call-a-method-from-a-string-in-swift | |
import UIKit | |
class TestDevice1: NSObject { | |
@objc func getPressure() { | |
print("get Pressure for TestDevice1") | |
} | |
@objc func getBattery() { | |
print("get Battery for TestDevice1") | |
} | |
} | |
class TestDevice2: NSObject { | |
@objc func getPressure() { | |
print("get Pressure for TestDevice2") | |
} | |
@objc func getBattery() { | |
print("get Battery for TestDevice2") | |
} | |
} | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
testAction(className: "TestProject.TestDevice1", methodName: "getPressure") | |
testAction(className: "TestProject.TestDevice2", methodName: "getPressure") | |
} | |
func testAction(className: String, methodName: String) { | |
let cla = NSClassFromString(className) | |
if let cla = cla as? NSObject.Type { | |
let selector: Selector = Selector(methodName) | |
let instance = cla.init() | |
if (instance.responds(to: selector)) { | |
instance.perform(selector) | |
} else { | |
print("method not found") | |
} | |
} else { | |
print("class not found") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment