开发者

How can I do something when a runloop event is done processing?

开发者 https://www.devze.com 2023-01-03 19:00 出处:网络
I have some processing in my Cocoa app that sometimes ends up calling through a hierarchy of data to do a bunch of work as the result of an event. Each small piece creates and destroys some resources.

I have some processing in my Cocoa app that sometimes ends up calling through a hierarchy of data to do a bunch of work as the result of an event. Each small piece creates and destroys some resources. I don't want those resources around most of the time, but I would like to find a smart way of creating them before all the work and killing them at the end.

Short of making those buffers etc available globally from the "parent" or elsewhere, is there a way to know locally in some code when an event loop run has ended? Then I could create them if they're not there, and keep them until the run loop ends, reusing them for any subsequent calls before that time.开发者_JAVA技巧

EDIT: I'm not looking for suggestions on how to restructure my code, which I may do anyways. This issue just brought up the question for me of how to know when the runloop is done. If I were writing in, I dunno, Javascript, I'd use a setTimeout with zero to accomplish end-event cleanup. I suppose an NSTimer with an interval of zero might accomplish this too, but wondering if there's something cleaner.

Thanks.


Since you said "Cocoa" and "NSRunLoop", I'm going to assume you are on Mac OS X. As long as you are on Snow Leopard, you can use Grand Central Dispatch to solve this kind of problem very elegantly.

If on Leopard or later (or iPhone, for that matter), you can use NSOperations to do the same (with slightly more code).

All of this is discussed in the Concurrency Programming Guide.

Even if your algorithm isn't designed to be executed off of the Main thread -- outside of the Main event loop -- you could still solve the problem of scheduling stuff for "later", to be executed serially, via the main queue.


I'm relatively new to programming in Cocoa, but wouldn't this just be easily accomplished by a class-level variable with a getter to that variable?

Let's say your code is like this, in pseudocode:

bool completed = false;

void chi
  if completed = false
    create foo;
    create bar;

   completed = true 
  end if

  while looping
     ...
  loop

  completed = false;
  destroy foo
  destroy bar

And within other portions of your program, check the value of 'completed' to see whether or not said objects were created?

EDIT: I just reread your question and edited accordingly. If this is a multi-threaded app you'll also need to make sure that your objects are threadsafe.

0

精彩评论

暂无评论...
验证码 换一张
取 消