使用NSTimer传递原始参数的正确方法 [英] Proper way of passing a primitive argument with an 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 theuserInfo
parameter, I get anEXC_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 typedid
.YES
is a primitive, namely the value1
. In order to make sure theuserInfo
object does not get deallocated, the timer retains it. So, when you passedYES
, NSTimer was doing[(id)YES retain]
. Try that in your own code and see what happens. :-PAs 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 itYES
. 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屋!