How to create a startup pool when using [NSThread detachNewThreadSelector: toTarget: withObject:]

Hi, I use [NSThread detachNewThreadSelector: toTarget: withObject:] and I get a lot of memory leaks because I do not have an autostart pool configured for a single thread. I'm just wondering where am I really doing this? This is before I call

[NSThread detachNewThreadSelector:toTarget:withObject:]

or in a method that runs in another thread?

Any help would be appreciated, some sample code would be great.

Thank.

+3
source share
5 answers

in the method that you call with the thread ... i.e. with this in mind ...

[NSThread detachNewThreadSelector:@selector(doStuff) toTarget:self withObject:nil];

Your method will be ...

- (void)doStuff {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  //Do stuff
  [pool release];
}
+9
source

, , .

:

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

- (void) myMethod {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Here, add your own code
    // ...

    [pool drain];
}

, , autoreleasepool. iOS . Mac OS X, , . , .

+6

:

[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];

, .


- (void)myMethod
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // Your Code
    [pool release];
} 

, - (, )? performSelectorOnMainThread.

[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

: - iPhone SDK

+5

, . , , ( [NSOperation][1] Grand Central Dispatch: ).

, , ?

:

[NSThread detachNewThreadSelector: @selector(blah:) toTarget: obj withObject: arg]

:

[NSThread detachNewThreadSelector: @selector(invokeBlah:) toTarget: self withObject: dict]

- (void)invokeBlah: (id)dict {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  id obj = [dict objectForKey: @"target"];
  id arg = [dict objectForKey: @"argument"];
  [obj blah: arg];
  [pool release];
}

, NSInvocation, . , SO. .

+3

The documentation states that a method running in a thread should create and destroy its own auto-resource pool. Therefore, if your code has

[NSThread detachNewThreadSelector:@selector(doThings) toTarget:self withObject:nil];

Method should be

- (void)doThings {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  //Do your things here
  [pool release];
}
+3
source

All Articles