我正在编写一个将同时执行多项任务的应用程序。一项特定任务是每 200 毫秒执行一次。为此,我使用了两种相互调用的方法。第一个方法只调用第二个,第二个方法使用 dispatch_after() 延迟调用第一个。
经过几次迭代(300-400 次) dispatch_after 中的 block 在 200 毫秒后未执行。 执行 block 需要大约 5-10 秒。请让我知道行为(延迟)的原因。我也试过 NSThread (sleepForTimeInterval:),我也面临着同样的问题。我被卡住了。请帮助我。
代码如下。
屏幕.h
#import <Foundation/Foundation.h>
@interface Screen : NSObject
-(void) firstMethod;
-(void) secondMethod;
@end
屏幕.m
#import "Screen.h"
@implementation Screen
int i=0;
dispatch_queue_t another_queue;
dispatch_time_t pop_time;
-(Screen*) init {
self = [super init];
if (self) {
another_queue = dispatch_queue_create("com.test.timer.2", NULL);
}
return self;
}
-(void) firstMethod {
i++;
NSLog(@"i value : %d",i);
[self secondMethod];
}
-(void) secondMethod {
pop_time = dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC);
dispatch_after(pop_time, another_queue, ^(void){
[self firstMethod];
});
}
@end
AppDelegate.h
#import <Cocoa/Cocoa.h>
#import "Screen.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
Screen* screen = [[Screen alloc] init];
dispatch_queue_t first_queue = dispatch_queue_create("com.test.timer", NULL);
dispatch_block_t blk =^(void) {
[screen firstMethod];
};
dispatch_async(first_queue, blk);
}
@end
最佳答案
发生这种情况时,您的应用程序是否在前台?如果没有,您可能只是看到 App Nap 开始运行。它所做的其中一件事是限制后台应用程序中的计时器。
关于objective-c - dispatch_after() 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22164571/