开发者

(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];


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];


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜