Re: Why RunLoop?
Re: Why RunLoop?
- Subject: Re: Why RunLoop?
- From: Ken Thomases <email@hidden>
- Date: Mon, 16 May 2011 10:37:47 -0500
On May 16, 2011, at 10:25 AM, Nick Zitzmann wrote:
> On May 16, 2011, at 9:07 AM, Bing Li wrote:
>
>> I am a new programmer of Cocoa. When learning RunLoop, I felt a little bit
>> weird. Why should Cocoa provide such a technique? When programming on other
>> environments, a while-true loop and wait/pulse lock can be used to achieve
>> the same goal of RunLoop, right?
>
> Well, yes, pre-Carbon Classic Mac OS forced programmers to write their own run loops by polling for events, but why do that when there's code already written for you?
>
>> I notice that Cocoa threading can be programmed in the similar way. May I
>> ignore RunLoop?
>
> Only if you're doing some task that will start and exit, and doesn't have to handle events or timers or notifications. Otherwise, you need a run loop. NSApplication and UIApplication will run the main thread's run loop automatically. But if you, for instance, attach a timer to the run loop of another thread, then you need to run that thread's run loop or the timer will not trigger.
And this, in part, illustrates the "why" of run loops: the frameworks may install their own run loop sources into the main run loop. The way that run loops are implemented means that the specific code to handle an input source's "readiness" is encapsulated with the run loop source itself, not in the client code. So, the frameworks don't have to rely on the client code doing the right thing with their various different input sources.
In other words, a run loop can support a wide variety of different kinds of input sources without requiring client code to be updated to handle the new kinds of input. And, so long as the client code does run the run loop, the client can't mess up and fail to do something that the frameworks need to have done.
Regards,
Ken
_______________________________________________
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