How to initialize an object when controller pops up without blocking UI with GCD

In my application, I need to show the UIImagePickerController on button click. Here is the code I used in the method called by the button on the controller when it is clicked:

- (IBAction)choosePressed:(id)sender {
    if (!self.pickerController) self.pickerController = [[UIImagePickerController alloc]init];
        self.pickerController.delegate = self;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self.navigationController presentViewController:self.pickerController animated:YES completion:nil];
}

      

The problem is that UIImagePickerControllers are very slow to load, so I thought that moving the collector initialization in a method viewDidAppear:animated

, perhaps in a different thread, would be a good way to anchor the collector's creation / display process, so I did this:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    dispatch_queue_t myQueue = dispatch_queue_create("Picker Queue", NULL);
    dispatch_async(myQueue, ^{
    self.pickerController = [[UIImagePickerController alloc]init];
    self.pickerController.delegate = self;
    });
}

- (IBAction)choosePressed:(id)sender {
    self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self.navigationController presentViewController:self.pickerController animated:YES completion:nil];
}

      

That being said, the pickerController appears right after the button is clicked, but when the main controller loads, the UI freezes up a bit (possibly due to the pickerController initialization), but init has to be executed on a different thread, since I used the dispatch_async mechanism, right? Is there a bug in my code?

I am very new to GCD so I am missing something!

+3


source to share


1 answer


This is a misuse of UIKit to access it from a background thread. Perhaps you can show the "loading ..." screen. I think the best policy is not to worry about it.



+2


source







All Articles