0

我正在尝试设置 NSInovcation 系统以使用 performSelectorInBackground 将选择器启动到后台线程中: - 到目前为止,在实例方法 (-) 上运行系统时一切都成功,但我也想支持类方法 (+)。我已经调整了我的代码,为这两种类型的类提供了一个 invokeInBackgroundThread,除了一个问题之外,一切正常。当调用类方法时,我的控制台充斥着“autoreleased with no pool in place”消息。不知道是什么原因造成的。基于 DDFoundation 开源项目的代码如下所示。


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

1 回答 1

1

默认情况下,主线程具有自动释放池,如果您启动额外的线程 - 创建池是您的工作。其实这里没什么复杂的,只是

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

另外,如果您有很多线程,我建议您查看 NSOperation 而不是使用 [performSelectorInBackground] 运行线程。NSOperation(带有包装队列)是此类任务的更灵活的解决方案。

于 2010-08-27T13:21:02.137 回答