Wednesday, November 11, 2020

How to call methods using selectors

func getClass(_ classNameString: String) -> AnyClass {
  let clazz = objc_getMetaClass(classNameString)
  return clazz as! AnyClass
}

func callMethod2(clazz: AnyClass, method: String) -> AnyObject {
  let selector : Selector = NSSelectorFromString(method)
  let method = class_getInstanceMethod((clazz), selector)!
  let methodIMP : IMP! = method_getImplementation(method)
  let newAmountObj = unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(clazz,selector, nil) as AnyObject
  return newAmountObj
}

func callMethod(clazz: AnyClass, method: String) -> AnyObject? {
  let selector : Selector = NSSelectorFromString(method)
  guard let method = class_getClassMethod((clazz), selector) else { return nil }
  let methodIMP : IMP! = method_getImplementation(method)
  let newAmountObj = unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(clazz,selector, nil) as AnyObject
  return newAmountObj
}

func callMethod(classNameString: String, method: String) -> AnyObject? {
  let clazz: AnyClass = getClass(classNameString)
  let newAmountObj = callMethod(clazz: clazz, method: method)
  return newAmountObj
}