Search code examples
iosgrand-central-dispatchdispatch

How to stop dispatch_queue in ios?


I want to know the way for stopping asyncronous task when i click back button in navigation bar.I have done this code,but its not working ... dispatch_group_t imageQueue = dispatch_group_create();

dispatch_group_async(imageQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                     ^{
                         imagedata=[[NSMutableArray alloc]init];

                         for (int i=0; i<[imageURL count]; i++)
                         {
                             NSLog(@"clicked ");

                           [imagedata addObject:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[imageURL objectAtIndex:i]]]]];

 [[NSNotificationCenter defaultCenter] postNotificationName:@"Avatardownloaded" object:imagedata   userInfo:nil];
                             }




                     });

in viewdisappear....

-(void)viewDidDisappear:(BOOL)animated
{
    dispatch_suspend(imageQueue);

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Avatardownloaded" object:nil];
    [[NSNotificationCenter defaultCenter]release];
    [avatarimages release];
    [imagedata release];
    [imageURL release];   
}

even though i suspend the thread it doesnt stop execution its keepon running in background.Anyone pls help me


Solution

  • Grand Central Dispatch is suitable for fire-and-forget tasks. If you want cancellable tasks, I would recommend using NSOperation and maybe NSOperationQueue.