views:

32

answers:

2

I'd like to create a View/Window that performs some inital loading in my application. I tried something like this:

StartWindow *start = [[StartWindow alloc] initWithNibName:@"Start" bundle:nil];

self.startWindow = start;

[start release];

[window addSubview:startWindow.view];

And in the viewDidLoad event inside StartWindow for the time being I just have [NSThread sleepForTimeInterval:3.0]; to simulate my loading.

The problem is that my view doesn't display until after the thread finished sleeping. why?

Edit

The above code is inside didFinishLaunchingWithOptions.

+1  A: 

The problem is that you block the main thread and thus the OS can't refresh the window and display your new view. You could try to perform the loading in a second thread, or, if you need to call a lot of non threadsafe functions, you could start the loading after a short amount of time via an NSTimer so that the OS has time to refresh the window.

Another way is to perform the loading in viewDidAppear: which gets invoked when the view is displayed while viewDidLoad gets invoked when the view got loaded from the nib file.

JustSid
Same thing with `viewDidAppear`.
Filip Ekberg
If it also doesn't work inside viewDidAppear, you might want to try out the timer method? So you don't need to load in the background but you give the OS time to refresh the window.
JustSid
+1  A: 

Because the framework is waiting for you to finish initialising the view in viewDidLoad. If you want loading to happen in the background you have to use some kind of background processing facility, like a separate thread or NSOperationQueue.

BTW, sleepForTimInterval doesn't actually run in a separate thread. It makes the calling thread sleep (in this case, the main UI thread).

Marcelo Cantos
So is there anything I can do to fix it? I don't want to load in the background, I want to display information about the loading after it's loaded, therefore I want to wait until it's finished.
Filip Ekberg
Then you need to do the work in a separate thread, which signals the main thread when it's done. A low-level thread can do this via `performSelectorOnMainThread`. NSOperationQueue may have its own signalling mechanisms, but I haven't used it much.
Marcelo Cantos
You you have any examples on how to get started with `performSelectorOnMainThread`? I still don't think this solves my problem. After this view has loaded and displayed the data, I am removing it and displaying another view, that's why I want to wait for it to finish.
Filip Ekberg
The `performSelectorOnMainThread` call is simply a way to have arbitrary code run in the main thread as soon as the background loading thread finishes its business. You can invoke it on the app delegate and have it destroy the startup view and fire up the main view. If you want examples, just google for them. [Here's](http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/) one I found.
Marcelo Cantos