Vladislav Shtepin
Vladislav Shtepin

Reputation: 15

Objective-C, call method and wait for nested threads

I've got a class ("MyClass") which public interface consists of one method and one int field.

Public method ("execute") gets some values from application and launches another private method ("execute:withId:") passing these values as arguments. Private method does some preparing and launches network interaction (uploading files, api interaction) method in a separate thread. Finally API returns int value ("Id") which is put into public int field.

In another class i have method which should do some operation on this Id, like

MyClass* c = [Global getMyClassInstance];
[c execute];
int Id = [c getId];

Problem is, until all threads created after [c execute] called Id is nil, and i can't find how to wait until all threads are done.

I've tried:

        [c performSelectorOnMainThread:@selector(execute) withObject:c waitUntilDone:YES];

But it doesn't wait. I've also tried dispatch_group with same results. And NSOperationQueue tries to execute selector on NSOperationQueue not an object passed as withObject.

Upvotes: 1

Views: 214

Answers (1)

alediaferia
alediaferia

Reputation: 2617

If you can switch to an async approach (which is better IMO, since you are interacting with networking and APIs), you should make your class use a delegate and invoke the appropriate delegate method when the execution is finished.

Otherwise you should make your execute method block until the networking and API interaction is finished: this can be achieved through the -[NSURLConnection sendSynchronousRequest:returningResponse:error:] method.

Upvotes: 1

Related Questions