1

There is a task needs to draw N images on a NSView. But at the beginning I do not know the amount of images, so I set it works in a thread of background.

 [NSThread detachNewThreadSelector:@selector(workInBackgroundThread:) toTarget:self withObject:nil];

when it get the amount of images, it will send a notification

- (void)workInBackgroundThread:(id)unusedObject {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//get image amount....

[[NSNotificationCenter defaultCenter] postNotificationName:@"gotImageAmount" object:nil];

//...
//continue to load images

}

I try to resize the NSView depends on the amount of images in the notification function

-(void)processGotImagesAmount:(NSNotification*)notification  
{

    //others codes

    [myNSView setFrame:CGRectMake(0,   0, calculateNewWidth, caculatedNewHeight)];//line A

    //others codes

}

but when the app executes the line A, it freezes,

[myNSView setFrame:CGRectMake(0,   0, calculateNewWidth, caculatedNewHeight)];

itself has no problem, if I click a bottun to call it, it works!

but it looks like it does not work in a notification function

Welcome any comment

bryanmac
  • 38,941
  • 11
  • 91
  • 99
monsabre
  • 2,099
  • 3
  • 29
  • 48

1 Answers1

7

You're posting the notification from the background thread.

From the NSNotificationCenter docs:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted

In your notification handling code you're updating ui which you must do from the main thread. Try moving that code to another method and then in the notification handling code, call it with performSelectorOnMainThread.

Another option is GCD without notifications. I posted a sample in this S.O. answer:

GCD, Threads, Program Flow and UI Updating

Community
  • 1
  • 1
bryanmac
  • 38,941
  • 11
  • 91
  • 99