我正在尝试访问 iOS 私有(private)函数 _setApplicationIsOpaque:
(仅供个人使用和测试)。
我已经实现了这段代码:
@_silgen_name("_setApplicationIsOpaque:") func _setApplicationIsOpaque(_ arg1: Bool)
let invokeSetApplicationIsOpaque: (Bool) -> Void = {
// The Objective-C selector for the method.
let selector: Selector = Selector(("_setApplicationIsOpaque:"))
guard case let method = class_getInstanceMethod(UIApplication.self, selector), method != nil else {
fatalError("Failed to look up \(selector)")
}
// Recreation of the method's implementation function.
typealias Prototype = @convention(c) (AnyClass, Selector, Bool) -> Void
let opaqueIMP = method_getImplementation(method)
let function = unsafeBitCast(opaqueIMP, to: Prototype.self)
// Capture the implemenation data in a closure that can be invoked at any time.
return{ arg1 in function(UIApplication.self, selector, arg1)}
}()
extension UIApplication {
func setApplicationIsOpaque(_ isOpaque: Bool) {
return invokeSetApplicationIsOpaque(isOpaque)
}
}
我在以下 StackOverflow 问题 Access Private UIKit Function Without Using Bridging Header 中找到了这种访问私有(private) iOS API 的方法 在this file在 GitHub 上。
问题是运行应用程序时出现错误
[UIApplication _setBackgroundStyle:]: unrecognized selector sent to class 0x10437f348
我找到了 UIApplication 的 iOS 私有(private) API 的 header in this GitHub repository .
最佳答案
- (void)_setApplicationIsOpaque:(BOOL)arg1;
是实例方法(属于UIApplication
),如
初始连字符 -
。实例方法被发送到一个实例
类,而不是类本身。
Objective-C 方法是带有两个隐藏参数的 C 函数,比较 Messaging 在《Objective-C Runtime Programming Guide》中:
It also passes the procedure two hidden arguments:
- The receiving object
- The selector for the method
对于实例方法,“接收对象”是实例
发送消息的对象,在您的例子中是 UIApplication
实例。
(对于类方法,它将是类对象)。
因此 Swift 扩展方法 setApplicationIsOpaque
必须将 self
传递给闭包,并且必须将其传递为
实现方法的第一个参数:
let invokeSetApplicationIsOpaque: (UIApplication, Bool) -> Void = {
// The Objective-C selector for the method.
let selector = Selector(("_setApplicationIsOpaque:"))
guard case let method = class_getInstanceMethod(UIApplication.self, selector), method != nil else {
fatalError("Failed to look up \(selector)")
}
// Recreation of the method's implementation function.
typealias Prototype = @convention(c) (UIApplication, Selector, Bool) -> Void
let opaqueIMP = method_getImplementation(method)
let function = unsafeBitCast(opaqueIMP, to: Prototype.self)
// Capture the implemenation data in a closure that can be invoked at any time.
return { (appl, arg1) in function(appl, selector, arg1)}
}()
extension UIApplication {
func setApplicationIsOpaque(_ isOpaque: Bool) {
return invokeSetApplicationIsOpaque(self, isOpaque)
}
}
请注意,此处不需要 _silgen_name
声明。
@_silgen_name("_setApplicationIsOpaque:") func _setApplicationIsOpaque(_ arg1: Bool)
将 Swift 函数绑定(bind)到全局符号“_setApplicationIsOpaque”, 这是不存在的。如果您要添加对该函数的调用
_setApplicationIsOpaque(true)
然后构建应用程序将失败并出现链接器错误:
Undefined symbols for architecture x86_64: "__setApplicationIsOpaque:"
关于ios - 无法识别的选择器调用 "_setApplicationIsOpaque:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43720097/