开发者

NSTimer retain count increases, why?

I have a problem regarding NSTimer. See the following code:

NSTimeInterval timeInterval = 1.0f;
SEL selector = @selector(executeDataRefresh);

NSMethodSignature *methodSignature = [[ExecuteDataRefesh class] instanceMethodSignatu开发者_C百科reForSelector:selector];

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:executeDataRefresh];
[invocation setSelector:selector];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:  timeInterval invocation:invocation repeats:YES];

The object executeDataRefresh's retain count will now increase by 1 each invocation of method executeDataRefresh. So after 1 minute the retain count is 60.

I know the method retainCount shouldn't be used, but is this method really this "incorrect"?

How come?


The NSInvocation retains its target because it needs the target to still be around when the timer fires. That fact is sort of buried in the documentation for -[NSInvocation retainArguments]:

If the receiver hasn’t already done so, retains the target [...]
NSTimers always instruct their NSInvocations to retain their arguments, [...] because there’s usually a delay before an NSTimer fires.

This is what is meant when someone says "Framework classes may be retaining things without you knowing". Don't worry about absolute retain counts.

What you should perhaps be worrying about instead* is the fact that, every time you run this code (which you seem to indicate happens fairly often), you are creating a new NSInvocation and repeating NSTimer instance with exactly the same attributes as the last time, which seems like a waste of memory.


*Unless this is just test code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜