开发者

Transferring object ownership among threads?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜