如何使用 NSTimer 多次触发? [英] How to use NSTimer to fire off multiple times?

查看:77
本文介绍了如何使用 NSTimer 多次触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 RNG,并希望它每三秒响一次.到目前为止,我有

I have a RNG and want it to go off every three seconds. So far I have

var timer = NSTimer(timeInterval: 3, target: self , selector: randomnumbers, userInfo: nil, repeats: true)

func randomnumbers() {
    var rockNamesArray:[String] = ["bird", "rock2", "rock3"]

    var rockpos = Int(arc4random_uniform(UInt32(3)))
}

但是我有一堆错误消息,我不知道如何组织它们.

But I have a bunch of error messages and I'm not sure how to organize it.

编辑

此代码中的错误消息告诉我它有一个未解析的标识符self",而所有其他错误都只是因为我更改了此代码而发生的错误,例如未解析的标识符 rockNamesArray 和 Rockpos,它们在三个中发生了 4 次不同的代码行.

The error message in this code is telling me that it has an unresolved identifier "self" and all the other error s are just ones occuring because I have changed this code, like unresolved identifier rockNamesArray and rockpos which happen 4 times in three different lines of code.

EDIT2

如评论中所述,上面的代码被放置在一个类之外,这解释了 self 不起作用.但是在这种情况下如何解决定时器例程?

As stated in the comment the above code is placed outside of a class which explains that self is not working. But how to address the timer routine in this case?

推荐答案

它有一个未解析的标识符self"

it has an unresolved identifier "self"

听起来您提供的代码不是实例方法的一部分.self 是一个关键字,引用其代码正在执行的对象.如果您没有对象,则没有 self,因此会出现错误.为了解决这个问题,你可以传递一个指向其他具有 randomnumbers 选择器来代替 self 的对象的指针.

It sounds like the code you've provided is not part of an instance method. self is a keyword that refers to the object whose code is executing. If you don't have an object, there's no self, hence the error. To solve the problem, you could pass a pointer to some other object that has a randomnumbers selector in place of self.

这篇关于如何使用 NSTimer 多次触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆