Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 不理解target、#selector()和@objc在这段代码中是如何被错误使用的_Swift - Fatal编程技术网

Swift 不理解target、#selector()和@objc在这段代码中是如何被错误使用的

Swift 不理解target、#selector()和@objc在这段代码中是如何被错误使用的,swift,Swift,有人能给我解释一下为什么这不起作用吗 class MyClass{ @objc func doSomething(){ print("I did something"); } } let timer = Timer.scheduledTimer(timeInterval: 1.0, target: MyClass, selector: #selector(doSomething), userInfo: nil, repeats: true) ----

有人能给我解释一下为什么这不起作用吗

class MyClass{
@objc func doSomething(){
        print("I did something");
    }
}
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: MyClass, selector: #selector(doSomething), userInfo: nil, repeats: true)
----编辑--------

我发现这是可行的

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: MyClass(), selector: #selector(MyClass.doSomething), userInfo: nil, repeats: false)
有人能解释一下为什么目标需要是MyClass()而不是MyClass,为什么它需要是MyClass.doSomething而不是doSomething吗。因为我认为目标成为选择器的作用域

正确的代码

    var timer : Timer?
    
    func timerstarter(){
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(doSomething), userInfo: nil, repeats: true)
    }
    
    
    @objc func doSomething(){
        print("I did something");
    }

目标必须是一个object如何读取Timer.scheduledTimer的文档。。。你在告诉计时器做什么(选择器)和什么时候做(时间间隔),但你还必须说谁应该做。为什么计时器不在课堂上?它属于哪里?这实际上不起作用,因为没有定义self检查更新的代码。