将objective-c调用转换为swift

时间:2015-02-12 14:03:48

标签: ios swift

我正在尝试将一些Objective-C转换为Swift代码。

我如何转换它,因为我在swift中找不到任何等效物。

((void (*)(id, SEL, id, id))objc_msgSend)(anObject, mySelector, anotherObject, lastObject)

2 个答案:

答案 0 :(得分:6)

Swift 3.1

let handle : UnsafeMutableRawPointer! = dlopen("/usr/lib/libobjc.A.dylib", RTLD_NOW)
unsafeBitCast(dlsym(handle, "objc_msgSend"), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector),anotherObject,lastObject)
dlclose(handle)

您也可以使用class_getMethodImplementation

unsafeBitCast(class_getMethodImplementation(type(of: anObject), #selector(mySelector)), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector), anotherObject,lastObject)

答案 1 :(得分:2)

Objective-C Runtime Reference列出了所有运行时函数。

有些函数有Swift表示,有些则没有。例如,class_getName在Swift中可用,但sel_getName不是。

Swift无法使用函数objc_msgSend


快速搜索后,我发现了这个:Call a method from a String in Swift。为objc_msgSend创建一个Objective C包装器,它将为您完成工作。这不是一个好的答案,但它现在似乎是一个有效的解决方案。