我正在尝试设置一个NSInovcation系统,以便使用performSelectorInBackground启动选择器到后台线程:-到目前为止,在实例方法(-)上运行系统时,一切都是成功的,但我也希望支持类方法(+)。我已经对代码进行了调整,为这两种类型的类提供了一个invokeInBackgroundThread,除了一个问题之外,一切都正常工作。当调用类方法时,我的控制台会被“自动释放而没有池到位”的消息淹没。不知道是什么引起的。基于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];发布于 2010-08-27 13:21:02
主线程默认有自动释放池,如果启动额外的线程--创建池是您的工作。实际上,这里没什么复杂的,只是
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// Work...
[pool release];另外,如果您有很多线程,我建议您查看一下NSOperation,而不是使用performSelectorInBackground运行线程。对于这类任务,NSOperation (带包装队列)是更灵活的解决方案。
https://stackoverflow.com/questions/3584135
复制相似问题