0

I'm newbie with this so forgive me with any mistakes...

My situation:

- (id)initWith... //Some arguments

There's an initialization method that returns an object. It does a lot of work to set its instance variables with the values of the arguments. To maximize performance I divide the job in two threads. One thread sets a set of related variables and the other thread another bunch of them.

- (id)initWith:arguments {
self = [super init];
if (self) {
[NSThread detachNewThreadSelector:@selector(setFirstSetOfVariables:) toTarget:self withObject:argObject];
[self setSecondSetOfVariables:arguments];
//Check if the thread finished its work and return the value
return self;
}

To make it easy think both sets of vars that the method has to set don't have any relationship. Then my question is: how do I check if the first thread finished? I could create a BOOL var but I'd have to create a loop to check. I could also call a method to say it's ready. But as I don't know a lot of it, I don't know wether a method invoked inside a thread would be run in the main thread or in the other. Sorry. Thank you for any info.

Lluís
  • 578
  • 1
  • 5
  • 10
  • 1
    Is there a reason, you are doing so much work in the init method. I would think it is better to create the object and then call another method on the object to create all the other values. I would recommend that you read about GCD or other easy way of executing back ground jobs. Even Apple recommends against using NSThread class and infact relegated the discussion of NSThread even in its Concurrency Programming Guide. – Srikanth Dec 08 '12 at 22:29
  • 2
    What @Srikanth said; use of NSThread is generally discouraged. Doing heavy weight initialization in `init` is also discouraged. You really want to architect your app such that you can separate "set up all my objects" from "OK, GO!". – bbum Dec 09 '12 at 01:35

1 Answers1

0

You can do it this way to simplify the whole thing

ComplicatedObject *myComplicatedObject = [ComplicatedObject alloc] init;

[myComplicatedObject setLongTimeTakingVariables];

and in the ComplicatedObject create a method like

-(void)setLongTimeTakingVariables{
  dispatch_async(dispatch_get_global_queue(),^{ All of your code can go here. Infact you need not split it into two sections, because it will happen in the background and your userinterface will not get affected }

But if you want to split then you can do

   dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),^{  
                   some work here
     }

    dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),'{
                    some other work here
    }

Read the Concurrency Programming Guide and every thing is explained very clearly.

Srikanth
  • 1,725
  • 2
  • 10
  • 11