Slee
Slee

Reputation: 28248

prevent multiple dispatch_queue_create from being created in viewDidLoad

have a view that loads and a serial dispatch queue that is created, loads a ton of stuff in the background and works great. Problem is when I navigate back and forth to that view a new queue is created again and then I have multiple things doing the exact same work.

- (void)viewDidLoad {

dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
    dispatch_async(myQueue, ^{
        //function call to a helper outside the scope of this view 
    });
  }

How do I prevent this from happening?

EDIT: creating my own queue was not necessary so I change my code - same problem still exists.

Upvotes: 2

Views: 14179

Answers (3)

Joe
Joe

Reputation: 57169

Put it in the initialization code or move myQueue to an instance variable and then check for its existence.

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
    {
        dispatch_queue_t myQueue = dispatch_queue_create("com.mydomain.myapp.longrunningfunction", NULL);
        dispatch_async(myQueue, ^{
            //function call to a helper outside the scope of this view 
        });
        dispatch_async(myQueue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                dispatch_release(myQueue);
            });
        });
    } 
    return self; 
}

Or...

- (void)viewDidLoad {

    if(!_myQueue)
    {
        _myQueue = dispatch_queue_create("com.mydomain.myapp.longrunningfunction", NULL);
        dispatch_async(_myQueue, ^{
            //function call to a helper outside the scope of this view 
        });
        dispatch_async(_myQueue, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                dispatch_release(_myQueue);
            });
        });
    }
}

And if you only want it to run once during a single run of the application you can use dispatch_once

Upvotes: 3

malhal
malhal

Reputation: 30569

If using a storyboard put your initialization in here:

-(void)awakeFromNib{}

Upvotes: -1

Slee
Slee

Reputation: 28248

So here is a way to achieve what I really desire, prevent my dispatched queued items from running when my view is popped from the navigation stack:

I simple wrap this code around my code that is running in my dispatched queue:

-(void) myMethod {
  if (self.view.window) {
   //my code
  }
}

This came from watching the Blocks & Multithreading video here by Stanford: http://itunes.apple.com/us/itunes-u/developing-apps-for-ios-hd/id395605774

great video, helped lot.

Upvotes: 1

Related Questions