eugene
eugene

Reputation: 41745

(iphone) nsInvocation leaks .. maybe the passed arguments?

I'm calling a selector on background thread,
The selector has NSAutorelasePool around it.
I guess the arguments I pass to the selector is causing the problem. How should I deal with it?

  SEL theSelector;
    NSMethodSignature *aSignature;
    NSInvocation *anInvocation;

    theSelector = @selector(changeColor:forColorString:);
    aSignature = [[animationData class] instanceMethodSignatureForSelector:theSelector];
    anInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
    [anInvocation setSelector:theSelector];
    [anInvocation setTarget:animationData];
    // indexes for arguments start at 2, 0 = self, 1 = _cmd                                                                                                                                                                                                                   
    [anInvocation setArgument:&currentColor atIndex:2];
    [anInvocation setArgument:&nsColorString atIndex:3];

    [anInvocation performSelectorInBackground:@selector(invoke) withObject:NULL];

Upvotes: 0

Views: 475

Answers (2)

DougW
DougW

Reputation: 30055

In addition to what ughoavgfhw said, you also need to call [anInvocation retainArguments] if you intend to set objects as arguments and pass to a background thread.

Upvotes: 1

ughoavgfhw
ughoavgfhw

Reputation: 39925

When you tell the invocation to perform invoke in the background, the new thread is created with invoke being the first method called. Invoke does not create an autorelease pool, so anything autoreleased during that method will be leaked.

To fix this, use a wrapper method to perform the invocation.

- (void)performInvocation:(NSInvocation *)anInvocation {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    [anInvocation invoke];
    [pool release];
}

//where you were performing the invoke before:
[self performSelectorInBackground:@selector(performInvocation:) withObject:anInvocation];

Upvotes: 1

Related Questions