views:

455

answers:

2

Hi all,

how to use how to use NSRunLoop in objective-C and wait for some variable to change value ?

Thanks

+1  A: 

You would generally not use NSRunLoop directly in your code.

You would for example create GUI application which already has NSRunLoop in it (use predefined application code templates in Xcode).

It depends what the variable is that is supposed to change, you might have it somewhere inside your 'Model' object and it will be changed by some even like data arriving online, or linked to GUI object and user performed action.

  • If it is button you would setup handlers to invoke action.
  • If it is variable you would setup KVC/KVO to detect change and call handler.

And so on, Cocoa will handle the glue code for you, you just need to setup appropriate handling to perform action.

There's not enough details in your question, I would suggest having a look at some basic tutorial at Apple's site for developers to see what is available in Cocoa.

stefanB
+2  A: 

We would not normally use a NSRunLoop in production to wait for a variable to change. One could use a callback.

However, in unit test code we do have the following:

NSDate *twoSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:2.0];
    while (!callBackInvoked && !errorHasOccured && runCount-- &&  [[NSRunLoop currentRunLoop]  runMode:NSDefaultRunLoopMode beforeDate:twoSecondsFromNow]) {
     twoSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:2.0];
    }

The code waits until either our callback is invoked, an error occured or the number of 2 second periods we've waited for has occurred. We use this to test delegates that make callbacks.

As I said I would not do this in production code.

lyonanderson