将objective-c调用转换为swift

问题描述 投票:3回答:2

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

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

((void (*)(id, SEL, id, id))objc_msgSend)(anObject, mySelector, anotherObject, lastObject)
ios swift
2个回答
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)

2
投票

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

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

函数objc_msgSend不适用于Swift。


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

© www.soinside.com 2019 - 2024. All rights reserved.