Re: TextField not updated in a sheet for document-based Cocoa app
Re: TextField not updated in a sheet for document-based Cocoa app
- Subject: Re: TextField not updated in a sheet for document-based Cocoa app
- From: Graham Cox <email@hidden>
- Date: Tue, 12 Jun 2012 10:27:23 +1000
On 12/06/2012, at 12:29 AM, Gilles Celli wrote:
> the sheet is properly displayed (with its TextField and button) for the current document window, but the textField stringValue can't be set
> Maybe because it's the sheet is on a different thread ?…
>
> I've tried to get the sheet's textField string setting on the main queue to allow the update, but this doesn't work either….
> Does someone have any clues ?
> appendBlock = ^{
>
> dispatch_async(dispatch_get_main_queue(), ^{
> [[appendFilesSheet appendTextField] setStringValue:@"Appending Files..."];
> //[[appendFilesSheet appendTextField] setNeedsDisplay: YES];
> NSLog(@"[appendFilesSheet appendTextField] stringValue: %@", [[appendFilesSheet appendTextField] stringValue]);
> });
> };
>
> //Run the block on a different thread.
> dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
> dispatch_async(queue,appendBlock);
Since the text field is UI, you can't drive it from a thread other than the main thread. I think this includes calling its -setStringValue: method.
So you need to invoke that on the main thread - use [textField performSelectorOnMainThread:withObject:waitUntilDone:];
That will only work if you're not also blocking the main thread. I couldn't quite unravel your code, but it looks like nothing will happen because the main run loop isn't running while your loop is hogging the main thread. If you can do your files work on another thread, that could work, otherwise you'll have to break down the work your loop does and call it in pieces so that the normal work of the main thread is able to run. An easy way to do this is to use NSOperationQueue using the +mainQueue object which does the work (NSOperations) in pieces on the main thread. If your operations are thread-safe, this approach can be changed to a threaded approach by simply making an operation queue object of your own.
Another problem is that you start your work as soon as you've called beginSheet... on your panel. That method returns very quickly, and before the window itself is loaded, animated into position and run modally. That means your work has started before the window is available, so it may be that your references to its text fields are nil. It might be better to wait until the window is actually loaded (windowDidLoad) before doing your work, and make sure the work doesn't block the main thread.
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden