Linux 拨号vps windows公众号手机端

iOS中PerformSelector怎么使用

lewis 7年前 (2018-10-06) 阅读数 13 #程序编程
文章标签 iOS

在iOS中,performSelector方法用于调用对象的指定方法。

使用方法如下:

  1. 调用无参数方法:
let object = SomeClass()
object.performSelector(onMainThread: #selector(SomeClass.someMethod), with: nil, waitUntilDone: false)

上述代码将在主线程上调用SomeClasssomeMethod方法。

  1. 调用带有参数的方法:
let object = SomeClass()
let parameter = "Hello"
object.performSelector(onMainThread: #selector(SomeClass.someMethod(with:)), with: parameter, waitUntilDone: false)

上述代码将在主线程上调用SomeClasssomeMethod方法,并传递参数"Hello"

需要注意的是,performSelector方法默认只能调用没有返回值的方法。如果要调用有返回值的方法,可以使用perform方法配合NSInvocation来实现:

let object = SomeClass()
let invocation = NSInvocation()
invocation.target = object
invocation.selector = #selector(SomeClass.someMethod)
invocation.invoke()

上述代码将调用SomeClasssomeMethod方法,并获取返回值。

需要注意的是,performSelector方法在Swift中已经被废弃,推荐使用更安全的方式来调用方法,例如使用闭包或选择器(Selector)+协议的方式。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门