Reputation: 100200
What's the best way to sleep/wait until certain notification is posted?
I've got class with asynchronous API that gets data from NSNotification
(notification comes from Cocoa, I can't avoid it) and I need to unit test it.
So far I've figured out semi-busy wait:
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]
without processing of run loop notifications aren't received. But how can I break from run loop immediately when desired notification comes?
Upvotes: 2
Views: 973
Reputation: 21599
runMode:beforeDate: will run the loop just once, so you can use that call in a loop until you detect that the notification has been handled (if nothing else, your handler can flip a member variable in your test class to YES).
Upvotes: 2
Reputation: 44769
If this is just about unit testing your code's reaction to a notification, I think that causing the thread to sleep may be overkill. A few questions come to mind...
If you really need to create a multi-threaded scenario to test, you might look at testLockUnlock
in this unit test code for an example. (I was just trying to make sure that my code was properly using locks built into a collection or generalized mutable object.)
Upvotes: 1