Objective c 使用NSThread时探查器报告的泄漏。该项目是用ARC为目标C和iOS编制的
这就是我试图管理线程的方式Objective c 使用NSThread时探查器报告的泄漏。该项目是用ARC为目标C和iOS编制的,objective-c,ios,memory,automatic-ref-counting,memory-leaks,Objective C,Ios,Memory,Automatic Ref Counting,Memory Leaks,这就是我试图管理线程的方式 -(void)ExecuteThread { @autoreleasepool { bInsideDifferentThread = YES; //some code... bInsideDifferentThread = NO; } [NSThread exit]; } -(void)ThreadCallerEvent { NSThread *myThread = [[NSThread alloc] initWithTar
-(void)ExecuteThread {
@autoreleasepool {
bInsideDifferentThread = YES;
//some code...
bInsideDifferentThread = NO;
}
[NSThread exit];
}
-(void)ThreadCallerEvent {
NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(ExecuteThread) object:nil];
if (!bInsideThread)
[myThread start];
else
{
[myThread cancel];
}
}
我这样做是因为我不希望线程在完成工作之前启动。问题在于,这会从[NSThread init]
有没有办法解决这个问题?我运行了一个与您类似的片段,但无法检测到泄漏;但背景几乎肯定是不同的。我真的不确定ARC在您的示例中的
myThread
超出范围时做了什么。使用NSThread
的典型模式是:
[NSThread detachNewThreadSelector:@selector(executeThread)
toTarget:self
withObject:nil];
在这种情况下,您不负责直接处理正在分离的线程。(注意:我将您的方法名更改为使用camel case,这是Cocoa中首选的方法和变量命名约定。)
综上所述,管理线程是实现并行设计的关键。这是完全可以接受的;但苹果正在鼓励开发者迁移到GCD。从需要同时执行的工作单元的角度考虑要好得多
在这种情况下,如果不更深入地理解您的需求,就很难知道直接使用线程会给您带来什么好处(如果有的话);但我会考虑更仔细地看待并发队列/GCD。也许您可以简单地使用以下内容:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do your background work
});
并实现更清晰的并发设计,避免您现在看到的任何内存管理问题