2010-08-27 88 views
0

我試圖建立一個NSInovcation系統使用performSelectorInBackground推出選擇到後臺線程: - ( - )到目前爲止,一切都運行在實例方法系統時是成功的,但我也想支持類的方法(+) 。我已經調整了我的代碼,爲這兩種類的類提供了invokeInBackgroundThread,除了一個問題外,其他所有的東西都可以工作。當類方法被調用時,我得到我的控制檯充斥着「autoreleased沒有池到位」的消息。不知道是什麼原因造成的。下面顯示了基於DDFoundation開源項目的代碼。NSInvocation的泄漏


@implementation NSObject (DDExtensions) 
... 
+ (id)invokeInBackgroundThread 
{ 
    DDInvocationGrabber *grabber = [DDInvocationGrabber invocationGrabber]; 
    [grabber setInvocationThreadType:INVOCATION_BACKGROUND_THREAD]; 
    return [grabber prepareWithInvocationTarget:self]; 
} 

- (id)invokeInBackgroundThread 
{ 
    DDInvocationGrabber *grabber = [DDInvocationGrabber invocationGrabber]; 
    [grabber setInvocationThreadType:INVOCATION_BACKGROUND_THREAD]; 
    return [grabber prepareWithInvocationTarget:self]; 
} 
... 

... 
- (void)forwardInvocation:(NSInvocation *)ioInvocation 
{ 
    [ioInvocation setTarget:[self target]]; 
    [self setInvocation:ioInvocation]; 

if (_waitUntilDone == NO) { 
    [_invocation retainArguments]; 
} 

    if (_threadType == INVOCATION_MAIN_THREAD) 
    { 
     [_invocation performSelectorOnMainThread:@selector(invoke) 
             withObject:nil 
            waitUntilDone:_waitUntilDone]; 
    } else { 
     [_invocation performSelectorInBackground:@selector(invoke) 
            withObject:nil]; 
} 
} 
... 

+(void)doSomething; 
[[className invokeOnBackgroundThread] doSomething]; 

回答

1

主線程默認自動釋放池,如果你開始額外的線程 - 這是你的工作,以創建池。其實,這裏沒有什麼複雜的,只是

NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; 
// Work... 
[pool release]; 

另外,如果你有很多的線程,我建議你看一看的NSOperation而不是用[performSelectorInBackground]運行的線程。 NSOperation(帶包裝隊列)是這類任務更靈活的解決方案。