ios - 在 Swift 2、Xcode 7.0.1 中使用 'self'

标签 ios swift swift2 nstimer xcode7

我在类左大括号下方(在 viewDidLoad 之前)制作了一个计时器,用作整个类的变量。但是,当我尝试将计时器的目标设置为“self”时,出现错误:

Argument type 'NSObject -> () -> ViewController' does not conform to expected type 'AnyObject'

这是定时器的代码:

class ViewController: UIViewController { 

     var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)

最佳答案

以这种方式在类左大括号下方(在 viewDidLoad 之前)声明您的 timer:

var timer: NSTimer?

现在在您的 viewDidLoad 方法中添加此代码:

timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)

而且您可以在类里面的任何地方访问它。

关于ios - 在 Swift 2、Xcode 7.0.1 中使用 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314819/

相关文章:

objective-c - 用字符串数组填充 UITableView

swift - 从容器 View 访问导航栏

ios - 在 Swift 2.0 中自定义 UIButton 外观

unit-testing - 如何测试在 Swift 2 中引发错误的方法?

swift - ObjectMapper toJSON() 快速

ios - 在 Storyboard 中更改 super View 后保持自动布局约束

ios - 自动布局 UITableViewCell

ios - Swift NSNotificationCenter 不会触发

Swift:覆盖采用 NSInvocation 的初始化程序

ios - 如何获取当前 CLLocation 或 CLPlacemark 的 USA Region 和 Division?