开发者

Transferring object ownership among threads?

开发者 https://www.devze.com 2023-02-20 13:34 出处:网络
Suppose I have a background thread that creates an object. This object will eventually be needed to update the UI so it has to make it to the main thread.It seems awkward to alloc an object on one thr

Suppose I have a background thread that creates an object. This object will eventually be needed to update the UI so it has to make it to the main thread. It seems awkward to alloc an object on one thread and dealloc it on another thread. Is this common, or is there a better pattern? Consider:

// Called on a background thread
-(void)workerDoStuff
{
    MyObject *obj = [[MyObject alloc] init];
    [self performSelectorOnMainThread:@selector(updateUI:) withObject:obj];
}

// Performed on main thread
- (void)updateUI:(MyObject *)obj
{
  开发者_StackOverflow社区  // Do stuff with obj
    [obj release];
}

Thanks


From the documentation:

This method retains the receiver and the arg parameter until after the selector is performed.

So you can release obj in workerDoStuff after making the call, as it will be retained for you until updateUI: returns.

0

精彩评论

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

关注公众号