开发者

Load UIImagePickerController in background

When my app starts I would like to initialize an UIImagePickerController. Since this can take several seconds, I would like to do it in the background. What is the best way to ensure that the background task finished, before invoking the picker?

Currently I have the following code. It works, but it will crash if one invokes the picker before the background task is done.

 - (void) viewDidAppear: (BOOL)animated {

    [super viewDidAppear: animated];

    [self performSelectorInBackground:@selector(initPicker) withObject:nil];


    ....

 }

and

 - (void)  initPicker {
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

      NSLog(@"picker start... ");
      [self setPicker: [[UIImagePickerController alloc] init]];

      NSLog(@"picker done.");

      [pool release];

  } 

Thank you!

Edit: It turns our this question is somewhat theoretical. Computing [[UIImagePickerController alloc] init] only takes time in debug mode on the device. So for production code, there is no need to run anything in the background. Also, [[UIImagePickerController alloc] init] s开发者_Python百科eems to lock the main thread, so even in debug mode there is no advantage of placing it on a background thread.


Maybe a simple flag can do the job ?

@interface MyViewController : UIViewController
{
     BOOL _pickerIsLoaded;
}
@end

@implementation MyViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _pickerIsLoaded = NO;
    [self performSelectorInBackground:@selector(initPicker) withObject:nil];
}

- (void)initPicker
{
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

      NSLog(@"picker start... ");
      [self setPicker: [[UIImagePickerController alloc] init]];
      NSLog(@"picker done.");

      _pickerIsLoaded = YES;

      [pool release];

} 

@end


I would use NSConditionLock for signaling that your controller is loaded. In the -initPicker method I would set the condition when the UIImagePickerController is finish initializing. And in your IBAction for the showing the picker, I would check for that condition. For more options, see Threading Programming Guide.


Can you wait until your "picker done" and then add the picker view to whatever view makes it visible? Something like this, right after your "picker done" statment:

   [self presentModalViewController: theImagePickerController]; // assuming self is a viewController.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜