eugene
eugene

Reputation: 41725

How to make sure your delegate(iphone, cocoa) is thread safe?

I've seen a few examples of using delegate with multiple threads for async image loading with cocoa's URL loading system.

I think the process goes like below.

Thread 1 : give thread 2 an operation to perform, and a delegate which thread 2 will access upon completion.

Thread 2 : upon completing the operation, calls a predefined selector on the delegate passed by thread 1.

I'd like to implement similar feature(async processing with delegate) with my own classes. The below pseudo code is similar to the process outlined above, but i'd like to make it more detailed for the sake of discussion of thread safety.

Thread 1 :
[begin critical section]
set delegate so that thread 2 can access
[end critical section]
fire an operation

-(void) dealloc (of the delegate object's class) {
[begin critical section]
set delegate to null
[end critical section]
}

Thread 2 :
actually works on operation
- upon completion.. [begin critical section]
get delegate
[delegate performSelectorOnMainThread @someSelector];
[end critical seciton]

Now, I'm worried about the thread safety of accessing the delegate. In other words, how do the 2nd thread makes sure that the delegate is still valid when the delegate object can go away anytime without waiting for the operation completion.

The pseudo code above is the best attempt I've made and wonder if it's gonna actually work. Furthermore, I've never seen any attempt on making the delegate thread safe in similar work such as http://www.markj.net/iphone-asynchronous-table-image/ Isn't the critical section safe guarding necessary?

Thanks

Upvotes: 0

Views: 1199

Answers (2)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

You could simply have the worker retain its callback target. Then, it is guaranteed to be around when it goes to make the callback. This is what NSTimer does.

Upvotes: 1

BWW
BWW

Reputation: 515

NSURLConnection loads data on a secondary thread but only invokes delegate methods on the main thread, so from the perspective of consuming data from NSURLConnection you shouldn't have to worry about thread safety. It's taken care of within NSURLConnection.

As far as the delegate remaining valid goes, you would probably just want to keep a reference to your URL connections and cancel any pending or in-progress connections when your controlling object is deallocated.

-(void)cancel of NSURLConnection states:

"Once this method is called, the receiver’s delegate will no longer receive any messages for this NSURLConnection."

Upvotes: 2

Related Questions