views:

26

answers:

1

Hi, this is my first question here, so excuse me if I made any mistakes!

In my iPhone project I have a method running in a thread which takes a long time to execute (that's why it runs in a thread).

[NSThread detachNewThreadSelector:@selector(methodToBeCalledInAThread) toTarget:self withObject:nil];

// ...

-(void)methodToBeCalledInAThread {  
    MyClass *myClass = [[MyClass alloc] init];  
    [myClass setDelegate:self]; 
    [myClass veryIntensiveComputing];   
    [myClass release];
}

My goal is to notifiy the ViewController calling this method of any progress going on in this method. This is why I set the ViewController as a delegate of the class.

Now in the expensive method I do the following:

if(self.delegate != nil) {
    [self.delegate madeSomeProgress];
}

But unfortunately this does not work, because (I think) I'm in a background thread.

How do I achieve to notify the delegate of any changes with the method being executed asynchronously?

Thanks in advance!

Kind regards,
Sebastian

+2  A: 

Try [self.delegate performSelectorOnMainThread: @selector(madeSomeProgress) withObject: nil waitUntilDone: YES];....

See the documentation for details.

This will synchronously perform the operation on the main thread. As long as nothing in the main thread tries to execute stuff in that secondary thread, this is mostly safe to do.

However if you don't want to block the computation until the main thread services the request, you can pass NO to not wait. If you do so, then you also have to worry about thread synchronization. The main thread may not immediately service the request and, when it does, your background thread may be in the process of mutating state.

Threads are hard.

bbum
Indeed, they are. ;) The performSelectorOnMainThread method came to my mind some minutes ago.I ended up with adding another method in the background-thread-class, which is called by "performSelectorOnMainThread". So this method calls the delegate's method on the main thread and everything works fine. Thank you!
Sebastian Wramba