Search code examples
objective-cmultithreadingmemory-managementconventionsnsthread

Objective-C NSThread ref counting convention (retain vs autorelease)


My main program spawns a thread, which executes the following:

// alloc autorelease pool somewhere before
NSArray *blah = [NSArray arrayWithObject: @"moo"];
[self performSelectorOnMainThread: @selector(boonk:) withObject: blah
      waitUntilDone: NO];
// release autorelease pool somewhere after

Now, this seems buggy to me because the autorelease pool could be released before the selector boonk: is finished executing, which would cause a crash.

So, my natural next move would be:

// alloc autorelease pool somewhere before
NSArray *blah = [[NSArray alloc] initWithObject: @"moo"];
[self performSelectorOnMainThread: @selector(boonk:) withObject: blah
      waitUntilDone: NO];
// release autorelease pool somewhere after


- (void)boonk: (id)data
{
   // do something with data
   [data release];   // release the ref count the thread added
}

This definitely is bug-free, but .... seems unnatural. Is there an objective-c ref counting convention or protocol to handle this situation (cross thread NO-wait posting), or is the second solution above the way it's done?


Solution

  • Actually, performSelectorOnMainThread retains its arguments until after the selector is performed, so there's no need to do it.