使用NSTimer传递原始参数的正确方法 [英] Proper way of passing a primitive argument with an NSTimer

查看:278
本文介绍了使用NSTimer传递原始参数的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个基本的计时器来调用这个方法:

   - (void)refresh:(id)obj 
{
if(obj == YES)doSomething;
}

我想从我的代码的某些区域调用此方法,计时器

  [NSTimer scheduledTimerWithTimeInterval:refreshInterval 
target:self
selector:@selector b $ b userInfo:nil
repeats:YES];

当我把 YES userInfo 参数,我得到一个 EXC_BAD_ACCESS 错误;为什么是这样?



有人可以帮我做这个正确的方式,这样没有丑陋的投射等等?

它是键入 id YES 是一个原始值,即值 1 。为了确保 userInfo 对象不会被释放,定时器保留它。所以,当你通过 YES ,NSTimer做 [(id)YES retain] 。尝试在你自己的代码,看看会发生什么。 :-P



文档说明,您给出的选择器必须具有签名

   - (void)timerFireMethod:(NSTimer *)theTimer 
pre>

这意味着你不能有NSTimer调用任何方法 - 至少不直接。



所以,假设你有一个名为 refresh的方法,你可以使用上面的签名来创建一个特殊的方法, :,并且你想经常调用它,传递 YES 。您可以这样做:

  // somehere 
{
[NSTimer scheduledTimerWithTimeInterval:refreshInterval
target:self
selector:@selector(invokeRefresh :)
userInfo:nil
repeats:YES];
}

- (void)invokeRefresh:(NSTimer *)timer {
[self refresh:YES];
}

- (void)refresh:(BOOL)flag {
if(flag){
// do something
}
}


I'm using a basic timer that calls this method:

- (void) refresh:(id)obj
{
    if (obj == YES) doSomething;
}

I want to call this method from certain areas of my code and also from a timer

[NSTimer scheduledTimerWithTimeInterval:refreshInterval
                            target:self
                            selector:@selector(refresh:) 
                            userInfo:nil 
                            repeats:YES];

When I put YES as the argument for the userInfo parameter, I get an EXC_BAD_ACCESS error; why is this?

Can someone help me do this the right way so that there is no ugly casting and such?

解决方案

The userInfo parameter must be an object; it is typed id. YES is a primitive, namely the value 1. In order to make sure the userInfo object does not get deallocated, the timer retains it. So, when you passed YES, NSTimer was doing [(id)YES retain]. Try that in your own code and see what happens. :-P

As the Documentation states, the selector you give the method must have the signature

- (void)timerFireMethod:(NSTimer*)theTimer

This means you can't have an NSTimer invoke just any method—not directly at least. You can make a special method with the above signature which in turn invokes any method you want though.

So, say you have a method called refresh:, and you want to call it every so often, passing it YES. You can do this like so:

// somewhere
{
    [NSTimer scheduledTimerWithTimeInterval:refreshInterval
                                     target:self
                                   selector:@selector(invokeRefresh:)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)invokeRefresh:(NSTimer *)timer {
    [self refresh:YES];
}

- (void)refresh:(BOOL)flag {
    if (flag) {
        // do something
    }
}

这篇关于使用NSTimer传递原始参数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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