1

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

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

NSMethodSignature *methodSignature = [[ExecuteDataRefesh class] instanceMethodSignatureForSelector: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?

jscs
  • 63,694
  • 13
  • 151
  • 195
user521048
  • 79
  • 1
  • 6
  • can you add the code of the executeDataRefresh method? I suspect it has something to do with you problem. – ChristophK Sep 05 '11 at 14:39
  • 4
    if you know it shouldn't be used, why do you use it? – albianto Sep 05 '11 at 14:51
  • edo42: I had problem with memory management so in a desperate try to fix it I started to log the retainCount.. But yeah, you are right, it generated more questions than answers. – user521048 Sep 05 '11 at 17:50

1 Answers1

3

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.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195
  • I have read about setTarget: in http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSInvocation_Class/Reference/Reference.html It says "The object to assign to the receiver as target. " about the object set to target. The usage of word "assign" is interesting :) – user521048 Sep 05 '11 at 17:41
  • The use of the word "assign" there isn't likely to have anything to do with the `assign` keyword for declared properties, implying memory management. However, I was misremembering that `NSInvocation` _automatically_ retains its target. It does not, but an `NSTimer` causes it to do so, and I've added a reference to the docs that indicate this. – jscs Sep 05 '11 at 17:51