How to use NSRunLoop in objective-C?

How to use NSRunLoop in objective-C and wait for a variable to change value?

thanks

+4
source share
2 answers

Usually we did not use NSRunLoop in production to wait for a variable to change. You can use a callback.

However, in unit test code, we 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 our callback is called, an error has occurred or the number of 2 second periods that we have been waiting for has occurred. We use this to test delegates who make callbacks.

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

+5
source

Usually you do not use NSRunLoop directly in your code.

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

It depends on which variable needs to be changed, you can have it somewhere inside your Model object, and it will be changed by some, for example, such as data coming online or related to the GUI object and the actions performed by the user .

  • If this is a button, you can configure handlers to invoke the action.
  • If this is a variable, you must set KVC / KVO to detect changes and call the handler.

And so on, Cocoa will process the glue code for you, you just need to configure the appropriate processing to perform the actions.

There is not enough detail in your question, I would suggest taking a look at some basic tutorial on the Apple website for developers to find out what is available in Cocoa.

+1
source

All Articles