D.C.
D.C.

Reputation: 15588

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
{
    // Do stuff with obj
    [obj release];
}

Thanks

Upvotes: 1

Views: 155

Answers (1)

Anomie
Anomie

Reputation: 94794

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.

Upvotes: 2

Related Questions