NSNotification and NSView problem???

Discussion in 'Mac Programming' started by MayPeng, Jul 25, 2011.

  1. MayPeng macrumors member

    Nov 21, 2010
    Hello everyone,
    I am a freshman, and I am trying to make a mac application to upgrade some device, and get into trouble now. Here's the question:

    The project has a main window, which binds to the AppDelegate Controller; And has two threads: the parent-thread A shows the view, the child-thread B does something like upgrade and so on.

    Between two threads, I use the notification center to achieve Inter-Process Communication. When thread B finished doing something, it will sent a notification to thread A, and thread A will do some change on the view, such as change the values of some textfield and so on.

    The question is: sometimes the view shows correctly, and other times it fails to show the changed ones. How can I deal with it ?
  2. holmesf, Jul 25, 2011
    Last edited: Jul 26, 2011

    holmesf macrumors 6502a

    Sep 30, 2001
    Don't use NSNotificationCenter for communicating between threads. Notifications are always received on the same thread in which they were sent, in other words, it's probably not doing at all what you want it to. NSNotificationCenter is more geared towards implementing the Observer design pattern, not threading.

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

    You could use Grand Central Dispatch to schedule a block for execution on thread A's dispatch queue instead. Grand Central Dispatch will allow you to do this from thread B.

    /* In thread B */
    dispatch_async(dispatch_get_main_queue(), ^{
      /*   ... code you want to execute on thread A ... */
    Alternatively you can use NSObject's method to perform a selector on the main thread.


    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array
    Both methods are going to ultimately work by queuing some message on the application's run loop on the main thread for execution at a later time.

    There might be other methods for accomplishing this as well. Anybody?
  3. MayPeng thread starter macrumors member

    Nov 21, 2010
    Thanks for your help. I will try according to your suggestion.

Share This Page