On 16 May 2011, at 2:19 PM, Bing Li wrote:
> An application, AppController, which is interested in the asynchronous
> notification, is as follows. I put sleep(5) deliberately to test if the
> asynchronous notification works.

As far as the run loop is concerned, when you are in sleep(5) you are busy. In 
order for other events to be processed (including NSNotificationQueues) you 
need to return to the run loop (or recursively run the run loop again, but 
that's not usually the right thing to do).

If you're using a run loop, you should structure your program like this:
  1. Set up the run loop, creating input sources etc. to call your code when 
things happen.
  2. Start running the run loop, trusting it to call you when something happens.
     (If you're writing a GUI application, NSApplication does most of this for 
you.)
  3. Whenever your code is invoked, handle the event and return to the run 
loop. Never wait for anything! Instead, tell the run loop to call you when the 
thing happens, or after a delay if the thing doesn't happen.


If you have an operation that takes a long time, like a complex computation, 
then doing it when called from the run loop will make your application 
unresponsive while the operation is working. This is usually undesired. It's 
better to spawn a thread (or dispatch a block/function/method/NSOperation on a 
dispatch queue) to handle that computation and then pass the results back to 
the run loop when it is done. If you're waiting for network operations, don't 
block in read(): instead, create run loop sources for your socket (or use a 
higher level API such as NSURLConnection).


It's not necessary to use a run loop for non-GUI Cocoa programming. You can 
choose whether or not to, depending on what your program does. If your program 
will have a GUI, then it must use Cocoa's run loop.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to