ios - Is there any alternative for NSInvocation in Swift? -
i'm trying invoke selector, multiple (2+) arguments (the number of arguments can determined). however, selector unknown @ compile time (generated nsselectorfromstring, actually).
in objective-c, create invocation , set arguments , invoke it. not available in swift. there way around this? like:
let obj = someclass() let selector = nsselectorfromstring("arg1:arg2:arg3:") //selector, arguments known @ runtime //invoke selector
swift 3.1
nsinvocation
can used dynamically, fun exercise, not serious applications. there better alternatives.
class test : nsobject { var name : string? { didset { nslog("didsetcalled") } } func invocationtest() { let invocation : nsobject = unsafebitcast(method_getimplementation(class_getclassmethod(nsclassfromstring("nsinvocation"), nsselectorfromstring("invocationwithmethodsignature:"))),to:(@convention(c)(anyclass?,selector,any?)->any).self)(nsclassfromstring("nsinvocation"),nsselectorfromstring("invocationwithmethodsignature:"),unsafebitcast(method(for: nsselectorfromstring("methodsignatureforselector:"))!,to:(@convention(c)(any?,selector,selector)->any).self)(self,nsselectorfromstring("methodsignatureforselector:"),#selector(setter:name))) as! nsobject unsafebitcast(class_getmethodimplementation(nsclassfromstring("nsinvocation"), nsselectorfromstring("setselector:")),to:(@convention(c)(any,selector,selector)->void).self)(invocation,nsselectorfromstring("setselector:"),#selector(setter:name)) var localname = name withunsafepointer(to: & localname) { unsafebitcast(class_getmethodimplementation(nsclassfromstring("nsinvocation"), nsselectorfromstring("setargument:atindex:")),to:(@convention(c)(any,selector,opaquepointer,nsinteger)->void).self)(invocation,nsselectorfromstring("setargument:atindex:"), opaquepointer($0),2) } invocation.perform(nsselectorfromstring("invokewithtarget:"), with: self) } }
Comments
Post a Comment