#selector与闭包不兼容? [英] The #selector is not compatible with the closure?

查看:175
本文介绍了#selector与闭包不兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用闭包实现自定义功能。但是 #selector 不支持。

I have tried to implement the custom function with the closure. But it's does not supported by #selector.

这里有一个例子:

class Core: NSObject {

    static let shared:Core = Core.init()


    func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion: () -> Void) {

        button.layer.cornerRadius = button.bounds.width / 2
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = color
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.addTarget(viewController, action: #selector(completion()), for: .touchUpInside)
    }
}

Xcode给了我一个构建时间问题:

The Xcode gives me a build time issue:


'#selector'的参数未引用'@objc'方法,属性或初始化程序

Argument of '#selector' does not refer to an '@objc' method, property, or initializer


解决方案

选择器是一个字符串,用于标识Objective C运行时中的方法,属性和初始化程序。当您使用 #selector(SomeClass.SomeMethod(withParam:AndParam:)这样的表示法时,您将以一种编译器可以轻松解析并验证为的格式指定选择器。是正确的,但是最终,它将被简化为一个C字符串,例如: SomeMethodwithParam:AndParam:

A selector is a string that's used to identify methods, properties, initializers in the Objective C runtime. When you use a notation like #selector(SomeClass.SomeMethod(withParam:AndParam:), you're specifying the selector in a format that the compiler can parse easily and verify to be correct. But ultimately, that would just be reduced down into a C string like: "SomeMethodwithParam:AndParam:".

本质上,每个类都有一个字典,该字典将选择器映射到实现选择器的代码的函数指针。当使用选择器调用函数时,Objective C运行时在方法表中搜索有问题的类,并查找

Essentially, every class has a dictionary which maps selectors to the function pointers of the code that implements them. When a selector is used to invoke a function, the Objective C runtime searches the method table for the class in question, and looks up the method implementation corresponding to the given selector.

此过程无法使用闭包(根据定义是匿名的),因此,只能使用选择器是指在Objective C运行时中注册的方法,属性,初始化程序(隐式或显式地 @objc 的作用)。

There's no way for this process to work with closures, which are anonymous by definition. Thus, you can only use selectors to refer to methods, properties, initializers that are registered with the Objective C runtime (which is what @objc does, implicitly or explicitly).

这篇关于#selector与闭包不兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆