NSTimer 目标和 userInfo 参数问题
我已经阅读了 SO 并查看了 NSTimer 类的 Apple 文档,似乎创建计时器的最简单方法是使用以下方法:
[NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(fireThisMethod:)
userInfo:nil
repeats:NO];
我知道这将创建一个在 15 秒后触发的计时器。将被触发的方法将是传递到“选择器”中的任何方法(在本例中为“fireThisMethod”)。由于“重复”为“否”,这意味着它只会被触发一次。我的问题是:
1)是否可以将一种方法传递给具有多个参数的“选择器”?我见过没有任何参数的方法,或者在本例中为 1(因为方法名称后面有一个“:”)。诸如 fireThisMethod:anotherParameter:? 之类的方法
2)我不确定我是否真正理解“target”和“userInfo”参数的用途。你会有一个不是“自我”的“目标”吗?你会有一个不为零的“userInfo”吗?如果是,在什么场景下?
谢谢
I've read around SO as well as looked at the Apple documentation for the NSTimer class, and it seems like the easiest way to create a timer is by using the following method:
[NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(fireThisMethod:)
userInfo:nil
repeats:NO];
I understand that this will create a timer that fires after 15 seconds. The method that will be fired will be whatever method is passed into the "selector" (in this case "fireThisMethod"). Since the "repeats" is "NO," this means that it will only be fired once. My questions are:
1) Is it possible to pass in a method to "selector" that has more than one parameter? I've seen methods without any parameters, or in this case 1 (since a ":" is present after the method name). A method such as fireThisMethod:anotherParameter:?
2) I'm not sure if I truly understand what the "target" and "userInfo" parameters are for. Will you ever have a "target" that isn't "self?" Will you have a "userInfo" that isn't nil? If so, in what scenarios?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题 1
否。请查看 文档。引用:
不带参数的方法选择器是错误的。要传递的参数是
计时器,这样你就可以做一些事情,比如区分哪个计时器从你那里触发了
方法(如果多个计时器调用同一方法)。
问题 2a
目标可以是实现给定方法的任何对象。有时你可能会
想要一个特定的对象(除了自身)在计时器触发后执行任务。
问题 2b
这正是您正在寻找的内容。
userInfo
可以是任何对象,也许是数据容器、NSValue 或任何其他东西。用这个来传递额外的
您的方法将按如下方式提取信息:
Question 1
No. Take a look in the docs. Quoting:
Selectors for methods without arguments are wrong. The argument to be passed is
the timer, so you can do things like distinguishing which timer fired from you
method (in case more than one timer calls the same method).
Question 2a
The target can be any object that implements the given method. Sometimes you may
want a specific object (other than self) to do the task after the timer fires.
Question 2b
This is exactly what you're looking for.
userInfo
can be any object, maybe adata container, a NSValue, or any other thing. Use this to pass extra
information to your method which will extract it as follows: