How to set up an autorelease pool when using [NSThread detachNewThreadSelector:toTarget:withObject:]

前端 未结 5 422
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 17:35

Hi I\'m usuing [NSThread detachNewThreadSelector:toTarget:withObject:] and I\'m getting a lot of memory leaks because I have no autorelease pool set up for the detached thr

5条回答
  •  天命终不由人
    2021-01-14 18:35

    You have to set up an autorelease pool in the method you call and that will be executed in the new detached thread.

    For example:

    // Create a new thread, to execute the method myMethod
    [NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
    

    and

    - (void) myMethod {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        // Here, add your own code
        // ...
    
        [pool drain];
    }
    

    Note that we use drain and not release on the autoreleasepool. On iOS, it has no difference. On Mac OS X, if your app is garbage collected, it will triggers garbage collection. This allows you to write code that you can re-use more easily.

提交回复
热议问题