iOS中PerformSelector怎么使用

iOS
890
2023/10/2 20:52:35
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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)+协议的方式。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: iOS中CocoaPods怎么使用