在运行循环的开始/结束处执行选择器 [英] Performing selector at beginning / end of run loop
问题描述
iOS中的所有事件和方法都使用 NSRunLoop
:用户事件,方法调用,旋转,计时器,连接等进行处理。
我的问题是:
如何在运行循环的精确时刻执行选择器作为开始,结束?
您可以创建一个 CFRunLoopObserver
块上循环进入和退出。您可以使用 CFRunLoopAddObserver
将您的观察器添加到运行循环中,并使用 CFRunLoopGetMain
获得要添加到的运行循环。 / p>
下面是一个使用这些的例子:
- )applicationDidFinishLaunching:(NSNotification *)aNotification
{
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(NULL,(kCFRunLoopEntry | kCFRunLoopExit),YES,0,^(CFRunLoopObserverRef observer,CFRunLoopActivity activity)
{
static unsigned long count = 0;
NSLog(@activity%lu:%@,++ count,(activity& kCFRunLoopEntry?@Enter:@Exit));
});
CFRunLoopAddObserver(CFRunLoopGetMain(),observer,kCFRunLoopCommonModes);
}
这只是安装一个观察者,退出到运行循环。
请注意, CFRunLoopObserverCreateWithHandler
返回您拥有的引用,如果您删除观察者,您将负责解除分配。
All events and methods in iOS are processed using NSRunLoop
: user events, method calls, rotations, timers, connections, etc.
My question is:
How can I perform a selector in a precise moment of the run loop as the beginning and the end?
You can create a CFRunLoopObserver
which will call a block on loop entry and exit. You use CFRunLoopAddObserver
to add your observer to the run loop, and CFRunLoopGetMain
to obtain the run loop to add to.
Here is a rather pointless example using these:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(NULL, (kCFRunLoopEntry | kCFRunLoopExit), YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity)
{
static unsigned long count = 0;
NSLog(@"activity %lu: %@", ++count, (activity & kCFRunLoopEntry ? @"Enter" : @"Exit"));
});
CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
}
This simply installs an observer which logs every entry & exit to the run loop. You can run it as a complete application in Xcode and see how many times the run loop goes around.
Note that CFRunLoopObserverCreateWithHandler
returns a reference you own, if you remove the observer you are responsible for deallocation.
这篇关于在运行循环的开始/结束处执行选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!