IOS Swift message dispatch with closure
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
class DataModel: NSObject { | |
var data = 1 | |
var callback: ((Any?) -> Unmanaged<AnyObject>?)? | |
} | |
class CustomClass: NSObject { | |
@objc func getValue(_ model: DataModel, completion callback: Any!) { | |
print("get Value for CustomClass") | |
if let callback = callback as? ((Any?) -> Unmanaged<AnyObject>?) { | |
print("closure is not nil") | |
_ = callback(model.data) | |
} | |
} | |
@objc func setValue(_ model: DataModel, completion callback: Any!) { | |
print("test11 set Value for CustomClass, val is: \(model.data)") | |
if let callback = callback as? ((Any?) -> Unmanaged<AnyObject>?) { | |
print("test11 closure is not nil") | |
_ = callback(model.data) | |
} | |
} | |
} | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let dataModel = DataModel() | |
executeAction(className: "TestProject2.CustomClass", methodName: "setValue:completion:", arg: dataModel) { result in | |
print("test11 execute setValue callback complete!!, result: \(String(describing: result))") | |
return nil | |
} | |
} | |
private func executeAction(className: String, methodName: String, arg: Any?, callback: ((Any?) -> Unmanaged<AnyObject>?)? = nil) { | |
let cla: AnyClass? = NSClassFromString(className) | |
if let cla = cla as? NSObject.Type { | |
let selector: Selector = Selector(methodName) | |
let instance = cla.init() | |
if (instance.responds(to: selector)) { | |
if let arg = arg, | |
let callback = callback { | |
instance.perform(selector, with: arg, with: callback) | |
} else if let arg = arg { | |
instance.perform(selector, with: arg) | |
} else { | |
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