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开发者_JAVA技巧 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.
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
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.
If using a storyboard put your initialization in here:
-(void)awakeFromNib{}
精彩评论