开发者

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

开发者 https://www.devze.com 2022-12-16 13:29 出处:网络
My main program spawns a thread, which executes the following: // alloc autorelease pool somewhere before

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

// alloc autorelease pool somewhere before
NS开发者_开发技巧Array *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?


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


The rule is simple; to pass an object from thread A to thread B, there must exist a hard retain. Now, as documented, -performSelectorOnMainThread: (and variants) do retain the objects until the method is finished executing, regardless of synchronous or asynchronous invocation.

However, it is generally sensible to maintain a retain-on-sending-thread-that-is-released-on-receiving-thread motif. It is explicit in intention and will support future refactorings, potentially to other models that do not do the automatic retain/release.

And, to repeat because it is important, autorelease pools cannot be used to preserve objects across threads.

0

精彩评论

暂无评论...
验证码 换一张
取 消