gpt4 book ai didi

ios - 协议(protocol)功能的 Swift 选择器?

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:56 25 4
gpt4 key购买 nike

我有这样的代码:

protocol FooP {
...
}

extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
doFoo()
}
}
class A : NSObject, UITableViewDataSource, FooP {
var timer : NSTimer?

...

func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: Selector("doFoo:"),
userInfo: nil,
repeats: true
)
}
}

不幸的是,当我启动定时器程序崩溃时它崩溃了

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[xyz.A doFoo:]: unrecognized selector sent to instance 0x7fb2041c4ac0'

我如何让它工作(我想在协议(protocol)中保留 doFoo 的实现)?

如果我将 doFoo 移动到 A 类定义中,一切正常,但正如我所说,我想在协议(protocol)内实现此功能。

换句话说,我需要这样的选择器

"Hey I point to function named "doFoo" that is implemented as extension to FooP"

现在选择器似乎在说

"Hey I point to function named "doFoo" that is implemented in A class"

最佳答案

尝试在您的 Playground 玩耍。您的麻烦是,不可能在协议(protocol)扩展中定义 @objc func。所以,看看可能的解决方法

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation

protocol FooP {
}

extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
print("dofoo")
doFoo()
}
}
class A: FooP {
var timer : NSTimer?
@objc func foo(timer: NSTimer) {
doFoo(timer)
}
func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: "foo:",
userInfo: nil,
repeats: true
)
}
}

let a = A()
a.startUpdating()

如果将 doFoo 移到 A 类中,为什么它对你有用?那是因为你的类继承自 NSObject,所以 @objc 关键字不是必需的。

关于ios - 协议(protocol)功能的 Swift 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35456549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com